经典的生产者和消费者模型

参考:https://www.bilibili.com/video/BV1op4y1S7KK?from=search&seid=3238887614432738305

package product;

import java.util.LinkedList;
import java.util.Queue;
import java.util.Random;

/**
 * @Author lihaiyu
 * @Date 2020/7/26 23:28
 */
public class ProducerAndConsumerDemo {
    public static void main(String[] args) {
        Buffer buffer = new Buffer();
        Consumer consumer = new Consumer(buffer);
        Producer producer = new Producer(buffer);
        consumer.start();
        producer.start();
    }
}
class Producer extends Thread{
    private Buffer buffer;
    public Producer(Buffer buffer){
        this.buffer = buffer;
    }
    @Override
    public void run() {
        for(int i = 0;i<10;++i){
            try {
                buffer.add(i);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            try {
                Thread.sleep(new Random().nextInt(1000));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
class Consumer extends Thread{
    private Buffer buffer;
    public Consumer(Buffer buffer){
        this.buffer = buffer;
    }
    @Override
    public void run() {
        for(int i = 0;i<10;++i){
            int val = 0;
            try {
                val = buffer.pull();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(val);
        }
    }
}
class Buffer {
    private Queue queue = new LinkedList<>();
    private int size = 5;

    public synchronized void add(int val) throws InterruptedException {
        if (queue.size() > size) {
            wait();//阻塞生产者,不让其继续生成
        }
        queue.add(val);
        notify();//通知消费者去消费
    }

    public synchronized int pull() throws InterruptedException {
        if (queue.size() == 0) {
            wait();
        }
        int val = queue.poll();
        notify();//通知生产者生产
        return val;
    }
}

经典的生产者和消费者模型_第1张图片

 

你可能感兴趣的:(Java)