问题描述
我后面是一个兼容的方式来配置线程池的使用或不。理想情况下,其余的代码不应该受到影响。我可以使用线程池1线程,但这不是我想要的。任何想法?
What I am after is a compatible way to configure the use of a thread pool or not. Ideally the rest of the code should not be impacted at all. I could use a thread pool with 1 thread but that isn't quite what I want. Any ideas?
ExecutorService es = threads == 0 ? new CurrentThreadExecutor() : Executors.newThreadPoolExecutor(threads);
// es.execute / es.submit / new ExecutorCompletionService(es) etc
推荐答案
这里有一个非常简单的 Executor
(不是 ExecutorService
)实现,只使用当前线程。从实践中的Java并发(基本阅读)窃取这个。
Here's a really simple Executor
(not ExecutorService
, mind you) implementation that only uses the current thread. Stealing this from "Java Concurrency in Practice" (essential reading).
public class CurrentThreadExecutor implements Executor {
public void execute(Runnable r) {
r.run();
}
}
ExecutorService
是一个更复杂的界面,但可以用相同的方法处理。
ExecutorService
is a more elaborate interface, but could be handled with the same approach.
这篇关于有没有使用当前线程的ExecutorService?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!