LinkedBlockingQueue 阻塞队列实现生产/消费模型
package com.example.demospringbootqueueasynctask;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import javax.annotation.PostConstruct;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
/***
* 通过阻塞队列实现 生产/消费模型的异步任务。
*/
@Service
public class QueueService {
private static Logger logger = LoggerFactory.getLogger(QueueService.class);
/**
* 使用阻塞队列实现 生产消费模型
* 下面例子中的数据类型暂定为String
*/
public static LinkedBlockingQueue<String> queue = new LinkedBlockingQueue<>();
/***
* 线程池,多线程任务处理
*/
private static ExecutorService threadPool = Executors.newFixedThreadPool(3);
//启执行
@PostConstruct
private void consumer() {
for (int i = 0; i < 3; i++) {
threadPool.execute(() -> {
while (true) {
String message = null;
try {
Thread.sleep(50);//休息
message = queue.take();
//模拟消费队列---->做一个输出操作
System.out.println("接收到消息:[" + Thread.currentThread().getName() + "]" + message);
} catch (Exception e) {
logger.error("企业知产同步队列发生了异常:", e);
//异常情况可以根据业务考虑是否需要重新放入队列
/*if (!StringUtils.isEmpty(message)){
queue.add(message);
}*/
}
}
}
);
}
}
/**
* 生产者
*/
public void producer(String message) {
if (StringUtils.isEmpty(message)) {
throw new RuntimeException("内容不能为空");
}
queue.add(message);
}
}
http://blog.xqlee.com/article/510.html