前述
- 生产者与消费者问题是线程并发问题中一个重要的内容,java有多种实现方式,而利用线程wait和notifyAll可以简单实现生产与消费并发的思想。
- 关键在于一个公共缓冲区用于存储当前生产的产品,生产和消费对同一个仓库(缓冲区)进行操作,这里使用LinkedList来模拟一个公共缓冲区,每次对缓冲区的操作都是从队尾进行添加删除。
代码区
package produce_consumer;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
/*
* 仓库模型
*/
public class Storage {
private static int maxsize;
private static List<Date> storage;
public Storage() {
maxsize = 10;
storage = new LinkedList<Date>();
}
public synchronized void set() {
if(storage.size() == maxsize) {
try {
wait();
}catch(InterruptedException e) {
e.printStackTrace();
}
}
storage.add(new Date());
System.out.println("product:"+storage.size());
notifyAll();
}
public synchronized void get() {
if(storage.size() == 0 ) {
try {
wait();
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
System.out.println("Consumer:第"+storage.size()+"个 : "+((LinkedList<?>)storage).poll());
notifyAll();
}
}
package produce_consumer;
/*
* 生产者
*/
public class Producer implements Runnable{
private Storage storage;
public Producer(Storage storage) {
this.storage = storage;
}
public void run() {
for(int i=0; i<10; i++) {
storage.set();
}
}
}
package produce_consumer;
/*
* 消费者
*/
public class Consumer implements Runnable{
private Storage storage;
public Consumer(Storage storage) {
this.storage = storage;
}
public void run() {
for(int i=0; i<10; i++) {
storage.get();
}
}
}
package produce_consumer;
public class MainThread {
public static void main(String[] args) {
Storage storage = new Storage();
Producer producer = new Producer(storage);
//生产者线程
Thread thread1 = new Thread(producer);
Consumer consumer = new Consumer(storage);
//消费者线程
Thread thread2 = new Thread(consumer);
thread1.start();
thread2.start();
}
}