生产者消费者问题是多线程的一个经典问题,它描述是有一块缓冲区作为仓库,生产者可以将产品放入仓库,消费者则可以从仓库中取走产品。
主要思路是利用BlockingQueue队列模拟实现仓库
put()方法:类似于我们上面的生产者线程,容量达到最大时,自动阻塞。
take()方法:类似于我们上面的消费者线程,容量为0时,自动阻塞。
生产者。
public class Producer implements Runnable {
BlockingQueue<String> queue;
public Producer(BlockingQueue<String> queue) {
this.queue = queue;
}
public void run() {
// TODO 自动生成的方法存根
try{
String temp = "A prodcut.生产线程:"
+ Thread.currentThread().getName();
System.out.println("I have made a Product:"
+ Thread.currentThread().getName());
queue.put(temp);//如果队列满的话,会阻塞当前线程
}catch(InterruptedException e) {
e.printStackTrace();
}
}
}
消费者
public class Consumer implements Runnable {
BlockingQueue<String> queue;
public Consumer(BlockingQueue<String> queue) {
this.queue = queue;
}
@Override
public void run() {
// TODO 自动生成的方法存根
try{
String temp = queue.take(); //如果队列为空,会阻塞当前线程
System.out.println(temp);
}catch(InterruptedException e) {
e.printStackTrace();
}
}
}
测试程序
public class Test {
public static void main(String[] args) {
BlockingQueue<String> queue = new LinkedBlockingQueue<String>(2);//设置缓冲区大小
Consumer consumer = new Consumer(queue);
Producer producer = new Producer(queue);
for(int i = 0; i < 5; i++) {
new Thread(producer,"Producer" + (i + 1)).start();
new Thread(consumer,"Consumer" + (i + 1)).start();
}
}
}
结果:
I have made a Product:Producer1
I have made a Product:Producer4
I have made a Product:Producer3
I have made a Product:Producer2
A prodcut.生产线程:Producer1
A prodcut.生产线程:Producer4
I have made a Product:Producer5
A prodcut.生产线程:Producer3
A prodcut.生产线程:Producer2
A prodcut.生产线程:Producer5