从oracle文档页面:
BlockingQueue实现是线程安全的。所有排队方法都可以使用内部锁或其他形式的并发控制原子地实现其效果
由于您已经在使用
BlockingQueues,因此可以删除
wait()和
notify()API。
使用的多个生产者和消费者的示例代码
BlockingQueue:
import java.util.concurrent.*;public class ProducerConsumerDemo { public static void main(String args[]){ BlockingQueue<Integer> sharedQueue = new linkedBlockingQueue<Integer>(); Thread prodThread1 = new Thread(new Producer(sharedQueue,1)); Thread prodThread2 = new Thread(new Producer(sharedQueue,2)); Thread consThread1 = new Thread(new Consumer(sharedQueue,1)); Thread consThread2 = new Thread(new Consumer(sharedQueue,2)); prodThread1.start(); prodThread2.start(); consThread1.start(); consThread2.start(); }}class Producer implements Runnable { private final BlockingQueue<Integer> sharedQueue; private int threadNo; public Producer(BlockingQueue<Integer> sharedQueue,int threadNo) { this.threadNo = threadNo; this.sharedQueue = sharedQueue; } @Override public void run() { for(int i=1; i<= 5; i++){ try { int number = i+(10*threadNo); System.out.println("Produced:" + number + ":by thread:"+ threadNo); sharedQueue.put(number); } catch (Exception err) { err.printStackTrace(); } } }}class Consumer implements Runnable{ private final BlockingQueue<Integer> sharedQueue; private int threadNo; public Consumer (BlockingQueue<Integer> sharedQueue,int threadNo) { this.sharedQueue = sharedQueue; this.threadNo = threadNo; } @Override public void run() { while(true){ try { int num = sharedQueue.take(); System.out.println("Consumed: "+ num + ":by thread:"+threadNo); } catch (Exception err) { err.printStackTrace(); } } } }它是如何工作的?
- 生产者线程1将整数从11到15放入
BlockingQueue
- 生产者线程2将范围为21-25的Integer放入
BlockingQueue
- 任何使用者线程-线程1或线程2从
BlockingQueue
(此示例中为Integer)读取值
样本输出:
Produced:21:by thread:2Produced:11:by thread:1Produced:12:by thread:1Produced:13:by thread:1Produced:14:by thread:1Produced:22:by thread:2Produced:23:by thread:2Produced:24:by thread:2Produced:25:by thread:2Consumed: 21:by thread:1Consumed: 12:by thread:1Consumed: 13:by thread:1Consumed: 14:by thread:1Consumed: 22:by thread:1Consumed: 23:by thread:1Consumed: 24:by thread:1Consumed: 25:by thread:1Produced:15:by thread:1Consumed: 11:by thread:2Consumed: 15:by thread:1



