高金亮丶
Published on 2019-11-12 11:31 with jnnleo丶

生产者消费者模式 用wait/notify实现

`package com.wlx.threadobjectclasscommonmethosd;

import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

/**

  • 生产者消费者模式 用wait/notify实现
    */
    public class ProducerConsumerModel {

    public static void main(String[] args) {
    EventStorage eventStorage = new EventStorage();
    Producer producer =new Producer(eventStorage);
    Consumer consumer = new Consumer(eventStorage);
    Thread thread = new Thread(producer);
    Thread thread1 = new Thread(consumer);
    thread.start();
    thread1.start();
    }

}
class Producer implements Runnable{
private EventStorage storage;
public Producer(EventStorage storage) {
this.storage = storage;
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
storage.put();
}
}
}

class Consumer implements  Runnable{

    private EventStorage storage;

    public Consumer(EventStorage storage) {
        this.storage = storage;
    }

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            storage.take();
        }
    }
}


 class EventStorage{
    private int maxSize;
    private LinkedList<Date> storage;
    public EventStorage(){
        maxSize=5;
        storage = new LinkedList<>();
    }
    public synchronized void put(){
        while (storage.size() == maxSize){
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        storage.add(new Date());
        System.out.println("创库里有了"+storage.size()+"产品");
        notify();//唤醒 沉睡的线程
    }

    public synchronized void take(){
        while (storage.size() ==0){
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("拿到了:"+storage.poll()+",现在仓库还剩下"+storage.size());
        notify();
    }

}

`

输出:
创库里有了1产品 拿到了:Fri Nov 27 20:19:26 CST 2020,现在仓库还剩下0 创库里有了1产品 创库里有了2产品 创库里有了3产品 创库里有了4产品 创库里有了5产品 拿到了:Fri Nov 27 20:19:26 CST 2020,现在仓库还剩下4 拿到了:Fri Nov 27 20:19:26 CST 2020,现在仓库还剩下3 拿到了:Fri Nov 27 20:19:26 CST 2020,现在仓库还剩下2 拿到了:Fri Nov 27 20:19:26 CST 2020,现在仓库还剩下1 拿到了:Fri Nov 27 20:19:26 CST 2020,现在仓库还剩下0 创库里有了1产品 创库里有了2产品 创库里有了3产品 创库里有了4产品 拿到了:Fri Nov 27 20:19:26 CST 2020,现在仓库还剩下3 拿到了:Fri Nov 27 20:19:26 CST 2020,现在仓库还剩下2 拿到了:Fri Nov 27 20:19:26 CST 2020,现在仓库还剩下1 拿到了:Fri Nov 27 20:19:26 CST 2020,现在仓库还剩下0

posted @ 2020-11-27 20:20  L-xxxx  阅读(75)  评论(0编辑  收藏  举报