我有多个生产者和单个消费者的阻塞队列(足以用于项目的后处理)。
生产者按计划启动,将任务发送到执行器池,然后工作人员将任务添加到队列中。
我的问题是如何启动消费者线程?
现在我有 @EventListener (SpringBoot),它在启动时发送到 singleThreadExecutorPool 方法,该方法在无限 while 循环中为队列提供服务,也许对于这种情况存在更好的解决方案。看起来是非常常见的消费队列模式。
最佳答案
你的方法非常好。 这是我个人处理此类情况的模式。
@Component
public class ConsumerTask implements Runnable {
private ExecutorService executorService;
private BlockingQueue<Object> queue;
// use dependency injection if needed
public ConsumerTask(BlockingQueue<Object> queue) {
executorService = Executors.newSingleThreadExecutor();
this.queue = queue;
}
@PostConstruct
public void init() {
executorService.execute(this);
}
@PreDestroy
public void destroy() {
// unlike shutdown() shutdownNow() sends interruption to running tasks
executorService.shutdownNow();
}
@Override
public void run() {
try {
while (true) {
Object o = queue.take();
// process o
}
} catch (InterruptedException e) {
// we were interrupted by shutdownNow(), restore interrupted status and exit
Thread.currentThread().interrupt();
}
}
}
关于Java - 单线程执行器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47031813/