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

  • 相关阅读:
    asp.net后台导出excel的方法:使用response导出excel
    asp.net后台导出excel的方法一:使用response导出excel
    infragistics--web网站升级注意点
    infragistics--网站部署时webtab的tab前出现textbox
    Jewels and Stones
    To Lower Case
    Unique Email Addresses
    unique-morse-code-words
    很久没来博客园了。。。。
    Centos7 基础知识---------root文件夹下没有.ssh文件
  • 原文地址:https://www.cnblogs.com/gbhh/p/13768119.html
Copyright © 2011-2022 走看看