生产者 / 消费者模型
用 wait() 和 notify() 来实现。
代码实现:
public class ProCumModel {
public static void main(String[] args) {
Buffer buffer = new Buffer();
Producer producer = new Producer(buffer);
Consumer consumer = new Consumer(buffer);
producer.start();
consumer.start();
}
}
/**
* 生产者
*/
class Producer extends Thread{
private Buffer buffer;
public Producer(Buffer buffer){
this.buffer = buffer;
}
@Override
public void run() {
for (int i=0;i<20;i++){
try {
buffer.add(i);
System.out.println("生产者生产数据" + i);
Thread.sleep(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<20;i++){
try {
int value = buffer.pull();
Thread.sleep(2000);
System.out.println("消费者消费数据" + value);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
/**
* 缓冲区
*/
class Buffer{
private Queue<Integer> queue = new LinkedList<>();
private int size = 5;
public synchronized void add(int value) throws InterruptedException {
if (queue.size() > size)
wait(); //阻塞生产者,不让其继续生产
queue.add(value);
notify(); //通知消费者去消费
}
public synchronized int pull() throws InterruptedException {
if (queue.size() == 0)
wait(); //阻塞消费者,不让其继续消费
int value = queue.poll();
notify(); //通知生产者去生产
return value;
}
}