阻塞队列实现生产者消费者
package com.example.demo;
import org.springframework.util.StringUtils;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
class ShareNewData {
/**
* 是否进行生产
*/
private volatile boolean FLAG = true;
private AtomicInteger atomicInteger = new AtomicInteger();
BlockingQueue<String> blockingQueue = null;
public ShareNewData(BlockingQueue<String> blockingQueue) {
this.blockingQueue = blockingQueue;
System.out.println(blockingQueue.getClass().getName());
}
public void prod() throws Exception {
System.out.println(Thread.currentThread().getName() + "\t生产线程启动!");
String date = null;
boolean reValue;
while (FLAG) {
date = atomicInteger.incrementAndGet() + "";
reValue = blockingQueue.offer(date, 2L, TimeUnit.SECONDS);
if (reValue) {
System.out.println(Thread.currentThread().getName() + "\t插入队列成功!");
} else {
System.out.println(Thread.currentThread().getName() + "\t插入队列失败!");
}
TimeUnit.SECONDS.sleep(1);
}
System.out.println(Thread.currentThread().getName() + "不在进行生产!FLAG表示等于false!");
}
public void consumer() throws Exception {
System.out.println(Thread.currentThread().getName() + "\t消费线程启动!");
String result = null;
while (FLAG) {
result = blockingQueue.poll(2L, TimeUnit.SECONDS);
//取不到,变换状态
if (StringUtils.isEmpty(result)) {
FLAG = false;
System.out.println(Thread.currentThread().getName() + "\t超过两秒钟没有取到,消费退去!");
System.out.println();
System.out.println();
System.out.println();
System.out.println();
return;
}
System.out.println(Thread.currentThread().getName() + "\t消费队列成功!");
}
}
public void stop() throws Exception {
this.FLAG = false;
}
}
/**
* Created by Administrator on 2020/7/8.
* 阻塞队列实现生产者消费者
*
* @author qtx
*/
public class ProducerAndConsumerDemoTwo {
public static void main(String[] args) throws Exception {
ShareNewData shareNewData = new ShareNewData(new ArrayBlockingQueue<String>(10));
//生产
new Thread(() ->
{
try {
for (int i = 1; i <= 5; i++) {
shareNewData.prod();
}
} catch (Exception e) {
e.printStackTrace();
}
}, "t1").start();
//消费
new Thread(() ->
{
try {
for (int j = 1; j <= 5; j++) {
shareNewData.consumer();
}
} catch (Exception e) {
e.printStackTrace();
}
}, "t2").start();
TimeUnit.SECONDS.sleep(5);
System.out.println(Thread.currentThread().getName() + "\t5秒钟之后main线程叫停!");
System.out.println();
System.out.println();
System.out.println();
System.out.println();
shareNewData.stop();
}
}