是否有任何java.util.ExecutorService
实现可以简单地在调用线程中运行所有已执行的任务?如果默认情况下这不包含在 Java 中,是否有一个库包含这样的实现?
3 回答
您可以使用 Guava com.google.common.util.concurrent.MoreExecutors.sameThreadExecutor() 完全符合您的要求:https ://github.com/google/guava/blob/0434c5199c83c3f43b8b6a86c62e121d518fe7d0/guava/src/com/google/ common/util/concurrent/MoreExecutors.java#L267
编辑:该方法已重命名为 com.google.common.util.concurrent.MoreExecutors.newDirectExecutorService() https://github.com/google/guava/blob/f67ab864bde63fa6602b5688de0440957ffeaa2e/guava/src/com/google/common/util /并发/MoreExecutors.java#L369
我能找到的唯一现有实现是SynchronousExecutorService
- 不幸的是埋在骆驼图书馆的某个地方。
在此处粘贴源代码(不带注释)以供将来参考:
package org.apache.camel.util.concurrent;
import java.util.List;
import java.util.concurrent.AbstractExecutorService;
import java.util.concurrent.TimeUnit;
public class SynchronousExecutorService extends AbstractExecutorService {
private volatile boolean shutdown;
public void shutdown() {
shutdown = true;
}
public List<Runnable> shutdownNow() {
return null;
}
public boolean isShutdown() {
return shutdown;
}
public boolean isTerminated() {
return shutdown;
}
public boolean awaitTermination(long time, TimeUnit unit) throws InterruptedException {
return true;
}
public void execute(Runnable runnable) {
runnable.run();
}
}
你看过 java.util.concurrent.ThreadPoolExecutor 吗?