简体   繁体   English

Java - 单线程执行器

[英]Java - Single thread executor

I have blocking queue with multiple producers and single consumer (which enough for post processing of items).我有多个生产者和单个消费者的阻塞队列(足以对项目进行后期处理)。

Producers starts by schedule which send tasks to executor pool and then tasks adds by workers to queue.生产者按计划开始,将任务发送到执行器池,然后工作人员将任务添加到队列中。

My question about how to start consumer thread?我的问题是如何启动消费者线程?

For now I have @EventListener (SpringBoot) that send on start to singleThreadExecutorPool method which serve the queue in infinite while loop, maybe better solution exists for this case.现在我有 @EventListener (SpringBoot) 在开始时发送到 singleThreadExecutorPool 方法,该方法在无限循环中为队列提供服务,对于这种情况,可能存在更好的解决方案。 Looks like pretty common pattern for consuming queue.看起来是消费队列很常见的模式。

Your approach is perfectly fine.你的方法非常好。 Here is my personal pattern for such cases.对于这种情况,这是我个人的模式。

@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();
    }
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM