管程法

/**

  • 管程法, 测试生产者和消费者
    */
    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;
    }
    }

原文地址:https://www.cnblogs.com/gbhh/p/13768119.html