问题描述
我所追求的是一种配置线程池使用与否的兼容方式.理想情况下,其余代码根本不应该受到影响.我可以使用带有 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 Concurrency in Practice"(基本阅读)中窃取.
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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!