使用阻塞队列实现生产者-消费者
class MyResource {
private volatile boolean FLAG = true;
private AtomicInteger atomicInteger = new AtomicInteger();
private BlockingQueue<String> blockingQueue = null;
public MyResource(BlockingQueue<String> blockingQueue) {
this.blockingQueue = blockingQueue;
System.out.println(blockingQueue.getClass().getName());
}
public void produce() throws Exception {
String data = "";
boolean returnValue;
while (FLAG) {
data = atomicInteger.getAndIncrement() + "";
returnValue = blockingQueue.offer(data, 2L, TimeUnit.SECONDS);
if(returnValue) {
System.out.println(Thread.currentThread().getName() + "插入数据" + data + "成功");
}else {
System.out.println(Thread.currentThread().getName() + "插入数据" + data + "失败");
}
TimeUnit.SECONDS.sleep(1);
}
System.out.println(Thread.currentThread().getName()+"大老板叫停,FLAG = false,生产动作结束");
}
public void consume() throws Exception {
String result = null;
while (FLAG) {
result = blockingQueue.poll(2L, TimeUnit.SECONDS);
if(result == null) {
FLAG = false;
System.out.println(Thread.currentThread().getName() + "超时2秒没取到数据,消费退出");
return;
}
System.out.println(Thread.currentThread().getName() + "消费队列" + result + "成功");
}
System.out.println(Thread.currentThread().getName()+"大老板叫停,FLAG = false,消费动作结束");
}
public void stop() {
this.FLAG = false;
}
}
public class ProducerConsumerDemo {
public static void main(String[] args) throws InterruptedException {
MyResource myResource = new MyResource(new ArrayBlockingQueue<>(10));
new Thread(()->{
System.out.println(Thread.currentThread().getName() + "生产线程启动");
try {
myResource.produce();
} catch (Exception e) {
e.printStackTrace();
}
},"prod").start();
new Thread(()->{
System.out.println(Thread.currentThread().getName() + "消费线程启动");
try {
myResource.consume();
} catch (Exception e) {
e.printStackTrace();
}
},"consume").start();
TimeUnit.SECONDS.sleep(5);
System.out.println("5秒后停止,活动结束");
myResource.stop();
}
}