多个newSingleThreadExecutor与ExecutorService的newFixedThreadPool

问题描述 投票:6回答:2

在我的应用程序中,我有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();

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

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

我的问题:

  1. 有什么理由我更喜欢一种选择吗?
  2. 使用X线程生成线程池或生成X newSingleThreadExecutors更容易接受什么?
  3. Pro et contra的每种方法?
java multithreading concurrency threadpool executorservice
2个回答
4
投票

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

newCachedThreadPool();

这将为每个需要它的任务创建一个线程(而不是更多)

使用单个线程池的好处是你可以单独关闭池,或者为每个线程命名,但如果你不需要它,那只是开销。

注意:您可以使用setName(“我的任务”)更改线程的名称,这可能对调试/分析有用。

使用ExecutorService的一个技巧是它捕获任何未捕获的异常/错误并将其放入返回的Future对象中。通常这个Future被丢弃,这意味着如果你的任务意外死亡,它也可以默默地执行。

我建议你在循环外部进行try / catch(Throwable)并记录它,这样你就可以看到线程是否意外死亡。例如OutOfMemoryError


1
投票

除了关闭个别执行人之外,我认为以下选项没有任何好处。

numOfProc * newSingleThreadExecutor()

但是你有更多的选择。我更喜欢Executors的以下三种选择之一。

newFixedThreadPool
newCachedThreadPool
newWorkStealingPool

有关相关查询,请参阅以下SE问题:

Java's Fork/Join vs ExecutorService - when to use which?

How to properly use Java Executor?

Difference between Executors.newFixedThreadPool(1) and Executors.newSingleThreadExecutor()

© www.soinside.com 2019 - 2024. All rights reserved.