zoukankan      html  css  js  c++  java
  • 管程法

    /**

    • 管程法, 测试生产者和消费者
      */
      public class TestPC {
      public static void main(String[] args) {
      SynContainer container = new SynContainer();
      Producter producter = new Producter(container);
      Customer customer = new Customer(container);
      producter.start();
      customer.start();
      }
      }
      //需要生产者、消费者、产品、缓冲区
      class Producter extends Thread{
      SynContainer container;

      public Producter(SynContainer container) {
      this.container = container;
      }

      @Override
      public void run() {
      for (int i = 0; i < 100; i++) {
      this.container.push(new Chicken(i));
      System.out.println("生产了"+i+"只鸡");
      }
      }
      }
      class Customer extends Thread{
      SynContainer container;

      public Customer(SynContainer container) {
      this.container = container;
      }

      @Override
      public void run() {
      for (int i = 0; i < 100; i++) {
      System.out.println("消费了"+container.pop().id+"只鸡");
      }
      }
      }
      class Chicken{
      int id; //编号

      public Chicken(int id) {
      this.id = id;
      }
      }
      class SynContainer {
      // 容器大小
      Chicken[] chickens = new Chicken[10];
      // 计数
      int count = 0;
      public synchronized void push(Chicken chicken){
      if(count == chickens.length){
      try {
      // 等待消费者消费
      this.wait();
      } catch (InterruptedException e) {
      e.printStackTrace();
      }
      }
      chickens[count] = chicken;
      count++;
      // 通知消费者消费
      this.notifyAll();
      }

      public synchronized Chicken pop(){
      if(count == 0){
      try {
      // 等待生产者生产
      this.wait();
      } catch (InterruptedException e) {
      e.printStackTrace();
      }
      }
      count--;
      Chicken chicken = chickens[count];
      // 通知生产者生产
      this.notifyAll();
      return chicken;
      }
      }

  • 相关阅读:
    Studio更新
    gradle 两种更新方法
    Handler基本用法
    使用git克隆指定分支的代码
    Bugly最简单的配置方法
    setTag,getTage复用
    Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2
    Android应用如何跳转到应用市场详情页面
    bzoj千题计划249:bzoj5100: [POI2018]Plan metra
    bzoj千题计划248:bzoj3697: 采药人的路径
  • 原文地址:https://www.cnblogs.com/gbhh/p/13768119.html
Copyright © 2011-2022 走看看