public class testLinkedBlockingQueue{
//初始化阻塞队列容器(放产品)
static BlockingQueue<String> products = new LinkedBlockingQueue<>();
static Random r = new Random();
public static void main(String[] args){
//1个生产者线程
new Thread(()->{
for(int i=0;i<100;i++){//生产100个产品
try{
products.put("产品:"+i);
}catch (InterruptedException e){
e.printStackTrace();
}
},"生产者").start();
//5个消费者线程
for(int i=0;i<5;i++){
for(;;){//死循环,一直在消耗产品,如果产品为空则产品容器队列阻塞,等待产品生产
//消费者线程消费产品
System.out.println(Thread.currentThread().getName() +
"消费:" + products.take());
}catch(InterruptedException e){
}).start();
public class TestArrayBlockingQueue {
//初始化阻塞队列容器(放10个产品)
static BlockingQueue<String> products = new ArrayBlockingQueue<String>(10);
for(int i=0;i<100;i++){//生产100个产品(放在容量为10的容器里)
products.put("产品:"+i);//容器满了则阻塞等待消费者消费
System.out.println(Thread.currentThread().getName()+"消费:"+products.take());