这种模式满足三点要求:
(1)生产者生产数据到缓冲区中,消费者从缓冲区中取数据。
(2)缓冲区满时,生产者线程阻塞,进入等待状态。这期间消费者一旦取走数据,队列未满,就会唤醒阻塞的生产者。
(3)缓冲区空时,消费者线程阻塞,进入等待状态。这期间生产者一旦往队列中放入数据,就会唤醒阻塞的消费者。
阻塞队列
public class MyBlockingQueue {
private int maxSize;
private LinkedList<Integer> queue;
public MyBlockingQueue(int maxSize, LinkedList<Integer> queue) {
this.maxSize = maxSize;
this.queue = queue;
}
public synchronized void put() throws Exception {
while (queue.size()==maxSize){
System.out.println("队列已满,生产者"+Thread.currentThread().getName()+"进入等待");
wait();
}
Random random = new Random();
int num = random.nextInt(100);
System.out.println("队列未满,生产者"+Thread.currentThread().getName()+"生产数据"+num);
if (queue.size()==0){
notifyAll();
}
queue.add(num);
}
public synchronized void take() throws Exception {
while (queue.size()==0){
System.out.println("队列为空,消费者"+Thread.currentThread().getName()+"进入等待");
wait();
}
if (queue.size()==maxSize){
notifyAll();
}
System.out.println("队列有数据,消费者"+Thread.currentThread().getName()+"去出数据"+queue.remove());
}
}
生产者
public class Producer implements Runnable{
private MyBlockingQueue myBlockingQueue;
public Producer(MyBlockingQueue myBlockingQueue) {
this.myBlockingQueue = myBlockingQueue;
}
@Override
public void run() {
for (int i = 0; i < 5; i++) {
try {
myBlockingQueue.put();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
消费者
public class Customer implements Runnable{
private MyBlockingQueue myBlockingQueue;
public Customer(MyBlockingQueue myBlockingQueue) {
this.myBlockingQueue = myBlockingQueue;
}
@Override
public void run() {
for (int i = 0; i < 5; i++) {
try {
myBlockingQueue.take();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}