阻塞队列的生产者消费者
package com.xiaojie.jiehe.my;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
public class BlockQueueDemo {
public static void main(String[] args) {
MyResource myResource = new MyResource(new ArrayBlockingQueue<>(3));
new Thread(()->{
System.out.println("生产者开始");
myResource.produce();
},"生产者").start();
new Thread(()->{
System.out.println("消费者开始");
myResource.consumption();
},"消费者").start();
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
myResource.stop();
System.out.println("停止");
}
}
class MyResource{
private volatile boolean flag = true;
AtomicInteger atomicInteger = new AtomicInteger();
BlockingQueue<String> blockingQueue = null;
public MyResource(BlockingQueue<String> blockingQueue) {
this.blockingQueue = blockingQueue;
System.out.println(blockingQueue.getClass().getName());
}
public void produce(){
try {
String i;
boolean offer = true;
while (flag){
i = atomicInteger.incrementAndGet()+"";
offer = blockingQueue.offer(i,2L, TimeUnit.SECONDS);
if (offer){
System.out.println(Thread.currentThread().getName()+"\t生产"+i+"成功");
}else {
System.out.println(Thread.currentThread().getName()+"\t生产"+i+"失败");
}
TimeUnit.SECONDS.sleep(1);
}
System.out.println("生产结束");
}catch (Exception e){
e.printStackTrace();
}
}
public void consumption(){
try {
String i;
while (flag){
i = blockingQueue.poll(2L,TimeUnit.SECONDS);
if (i==null || i.equals("")){
flag = false;
System.out.println(Thread.currentThread().getName()+"两秒没取到,消费结束");
return;
}
System.out.println(Thread.currentThread().getName()+"\t消费了"+i);
}
}catch (Exception e){
e.printStackTrace();
}
}
public void stop(){
this.flag = false;
}
}
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/f80053d19a1aa1a542834c237daf9df8.png)