首页 > 其他 > 详细

管程法

时间:2021-02-09 22:08:34      阅读:38      评论:0      收藏:0      [点我收藏+]

管程法

生产者消费者模型

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

}

管程法

原文:https://www.cnblogs.com/immortal-mode/p/14394258.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!