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;
      }
      }

  • 相关阅读:
    开发流程
    团队模式
    android studio 中点击button加1或者减1
    登录注册界面的测试点
    用在线工具processOn画UML的用例图和时序图
    android studio中R文件丢失了
    第一次迭代任务
    WBS(work Breakdown Structure)
    #“速达” app NABCD分析
    “速达”app电梯演说
  • 原文地址:https://www.cnblogs.com/gbhh/p/13768119.html
Copyright © 2011-2022 走看看