多个newSingleThreadExecutor与ExecutorService的newFixedThreadPool

Mik*_* B. 6 java concurrency multithreading executorservice threadpool

在我的应用程序中,我有4个不同的进程,这些进程在一些小的暂停时永久运行.

当前版本的代码在单独的旧学校线程中执行每个进程:

Thread nlpAnalyzer = new Thread(() -> {

    // infine lop for auto restore in case of crash
    //noinspection InfiniteLoopStatement
    while (true) {
        try {
            // this method should run permanently, pauses implemented internally
            NLPAnalyzer.analyzeNLP(dbCollection);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
});

nlpAnalyzer.setName("im_nlpAnalyzer");
nlpAnalyzer.start();
Run Code Online (Sandbox Code Playgroud)

现在我想用这个代码重构这个代码ExecutorService.为了做到这一点,我可以使用至少两种方法:

  • newFixedThreadPool(numOfProc);
  • numOfProc * newSingleThreadExecutor().

我的问题:

  1. 有什么理由我更喜欢一种选择吗?
  2. 使用X线程生成线程池还是生成X newSingleThreadExecutors 更接受什么?
  3. Pro et contra的每种方法?

Pet*_*rey 4

鉴于每个任务都是一个无限循环,我会使用的是

newCachedThreadPool();
Run Code Online (Sandbox Code Playgroud)

这将为每个需要它的任务创建一个线程(仅此而已)

每个使用单个线程池的好处是您可以单独关闭池,或者为每个线程指定一个名称,但如果您不需要这样做,这只是开销。

注意:您可以使用 setName("My task") 更改线程的名称,这可能对调试/分析目的有用。

使用 ExecutorService 的技巧之一是它捕获任何未捕获的异常/错误并将其放置在Future返回的对象中。通常这Future会被丢弃,这意味着如果您的任务意外终止,它也可能会默默地执行。

我建议您在循环外执行 try/catch(Throwable) 并记录它,以便您可以查看线程是否意外死亡。例如内存不足错误