BlockingQueue
![](https://i-blog.csdnimg.cn/blog_migrate/0c3b7a4517253e796a02d8c15a34ce31.png)
适用场景:
生产者线程在一端生产,消费者线程在另一端消费,可以安全的实现生产者消费者问题(多个生产者 多个消费者)
生产者:
import java.util.concurrent.BlockingQueue;
public class Producer implements Runnable {
private BlockingQueue<String> blockingQueue;
public Producer(BlockingQueue<String> blockingQueue){
this.blockingQueue=blockingQueue;
}
@Override
public void run(){
String temp="Product";
System.out.println(Thread.currentThread().getName()+":product");
try {
blockingQueue.put(temp);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
消费者:
import java.util.concurrent.BlockingQueue;
public class Consumer implements Runnable {
private BlockingQueue<String> blockingQueue;
public Consumer(BlockingQueue<String> blockingQueue){
this.blockingQueue=blockingQueue;
}
@Override
public void run(){
System.out.println(Thread.currentThread().getName()+":consumer");
try {
blockingQueue.take();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
测试代码:
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
public class RunTest {
public static void main(String[] args) {
BlockingQueue<String> blockingQueue=new LinkedBlockingQueue<String>(1);
Producer producer=new Producer(blockingQueue);
Consumer consumer=new Consumer(blockingQueue);
for(int i=1;i<=5;i++){
new Thread(producer,"Producer"+i).start();
new Thread(consumer,"consumer"+i).start();
}
}
}
测试结果:
Producer1:Product
consumer1:Consumer
Producer2:Product
consumer2:Consumer
Producer3:Product
consumer3:Consumer
Producer4:Product
consumer5:Consumer
Producer5:Product
consumer4:Consumer
Process finished with exit code 0
还可以用来解决输出ABABABABAB的问题哦。