【发布时间】:2016-07-23 17:29:02
【问题描述】:
在我的应用程序中,我有 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()。
我的问题:
- 有什么理由让我更喜欢一个选项而不是另一个选项?
- 用 X 线程生成线程池或生成 X
newSingleThreadExecutors 更接受什么? - 每种方法的优缺点?
【问题讨论】:
-
选项 1 更常见且开销最小。
-
另一方面,您可以将无限循环内的代码重写为
Runnable,在运行时将其自身再次发布为执行程序服务。这样,多个任务甚至可以在一个线程上运行。
标签: java multithreading concurrency threadpool executorservice