我所追求的是一种兼容的方式来配置线程池的使用。理想情况下,代码的其余部分应该完全不受影响。我可以使用一个只有一个线程的线程池,但这并不是我想要的。有什么想法吗?
ExecutorService es = threads == 0 ? new CurrentThreadExecutor() : Executors.newThreadPoolExecutor(threads);
// es.execute / es.submit / new ExecutorCompletionService(es) etc
发布于 2011-07-05 21:59:14
这里有一个非常简单的Executor
实现(注意,不是ExecutorService
),它只使用当前线程。从"Java并发实践“(必读)中窃取这篇文章。
public class CurrentThreadExecutor implements Executor {
public void execute(Runnable r) {
r.run();
}
}
ExecutorService
是一个更复杂的接口,但也可以用同样的方法来处理。
发布于 2013-02-01 12:24:08
你可以使用芭乐的MoreExecutors.newDirectExecutorService()
,或者MoreExecutors.directExecutor()
,如果你不需要ExecutorService
的话。
如果包含Guava太重了,你可以实现一些几乎一样好的东西:
public final class SameThreadExecutorService extends ThreadPoolExecutor {
private final CountDownLatch signal = new CountDownLatch(1);
private SameThreadExecutorService() {
super(1, 1, 0, TimeUnit.DAYS, new SynchronousQueue<Runnable>(),
new ThreadPoolExecutor.CallerRunsPolicy());
}
@Override public void shutdown() {
super.shutdown();
signal.countDown();
}
public static ExecutorService getInstance() {
return SingletonHolder.instance;
}
private static class SingletonHolder {
static ExecutorService instance = createInstance();
}
private static ExecutorService createInstance() {
final SameThreadExecutorService instance
= new SameThreadExecutorService();
// The executor has one worker thread. Give it a Runnable that waits
// until the executor service is shut down.
// All other submitted tasks will use the RejectedExecutionHandler
// which runs tasks using the caller's thread.
instance.submit(new Runnable() {
@Override public void run() {
boolean interrupted = false;
try {
while (true) {
try {
instance.signal.await();
break;
} catch (InterruptedException e) {
interrupted = true;
}
}
} finally {
if (interrupted) {
Thread.currentThread().interrupt();
}
}
}});
return Executors.unconfigurableScheduledExecutorService(instance);
}
}
发布于 2015-01-19 16:00:08
Java 8风格:
Executor e = Runnable::run;
https://stackoverflow.com/questions/6581188
复制相似问题