管程法

管程法

生产者消费者模型

import java.util.ArrayList;
import java.util.List;

//测试生产者消费者模型
public class TestPC {
    public static void main(String[] args) {
        //容器
       Container container = new Container();
        //开启线程
       new Producer(container).start();
       new Consumer(container).start();
    }
}
//生成者
class Producer extends Thread{
    Container container;

    public Producer(Container container) {
        this.container = container;
    }

    @Override
    public void run() {
        for (int i = 1; i <= 20; i++) {
            try {
                container.push(new Dog(i));
                Thread.sleep(100);
                System.out.println("生成了-->"+i+"只狗");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
//消费者
class Consumer extends Thread{
    Container container;

    public Consumer(Container container) {
        this.container = container;
    }
    @Override
    public void run() {
        for (int i = 1; i <=20 ; i++) {
            try {
                container.pop();
                Thread.sleep(1000);
                System.out.println("消费了-->"+i+"只狗");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
//产品
class Dog{
    int id;

    public Dog(int id) {
        this.id = id;
    }
}
//缓存区 Container
class Container{
    //容器
    List<Dog> dogs = new ArrayList<Dog>();
    //计数器
    int count = 0;
    //添加产品
    public synchronized void push(Dog dog) throws InterruptedException {
        //如果计数器等于10,等待
        if (count == 10){
            this.wait();
        }
        //添加到容器
        dogs.add(dog);
        //计数器++
        count++;
        //通知消费者消费
        this.notifyAll();
    }

    public synchronized Dog pop() throws InterruptedException {
        //如果计数器等于0,等待
        if (count == 0){
            this.wait();
        }

        count--;
        Dog dog = dogs.get(count);

        //通知生成者生产
        this.notifyAll();

        return dog;
    }

}
posted @ 2021-02-09 21:30  immortal_mode  阅读(57)  评论(0)    收藏  举报