**
前言
**
生产者和消费者问题是线程模型中的经典问题:生产者和消费者在同一时间段内共用同一个存储空间,生产者往存储空间中添加产品,消费者从存储空间中取走产品,当存储空间为空时,消费者阻塞,当存储空间满时,生产者阻塞。
以下这些解法,其实本质上都是实现了一个阻塞队列。为空,则消费者阻塞,满了,则生产者阻塞。
**
1.使用wait()和notify()实现
**
这也是最简单最基础的实现,缓冲区满和为空时都调用wait()方法等待,当生产者生产了一个产品或者消费者消费了一个产品之后会唤醒所有线程。
public static void testProductConsumeByWaitAndNotify() {
final int size = 10;
final Queue<String> queue = new ArrayDeque<String>(size);
final Object lock = new Object();
Runnable producer = new Runnable() {
public void run() {
for(int i=0;i<30;i++) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
String msg = "消息:"+i;
//队列未满,一直往里放消息
synchronized (lock) {
while (size == queue.size()) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
queue.offer(msg);
lock.notifyAll();
}
System.out.println(msg+" 已发送");
}
}
};
Runnable consumer = new Runnable() {
public void run() {
while (true) {
try {
Thread.sleep(200);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
synchronized (lock) {
while (queue.size() == 0) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
String msg = queue.poll();
System.out.println(msg+"已消费");
lock.notifyAll();
}