Are there any java.util.ExecutorService
implementations which simply run all executed tasks in the calling thread? If this isn't included in Java by default, is there a library which contains an implementation like this?
问题:
回答1:
The only existing implementation I could find is SynchronousExecutorService
- unfortunately buried somewhere in camel library.
Pasting source code (without comments) here for future reference:
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();
}
}
回答2:
You may use Guava com.google.common.util.concurrent.MoreExecutors.sameThreadExecutor() which does exactly what you want: https://github.com/google/guava/blob/0434c5199c83c3f43b8b6a86c62e121d518fe7d0/guava/src/com/google/common/util/concurrent/MoreExecutors.java#L267
EDIT: The method has been renamed to com.google.common.util.concurrent.MoreExecutors.newDirectExecutorService() https://github.com/google/guava/blob/f67ab864bde63fa6602b5688de0440957ffeaa2e/guava/src/com/google/common/util/concurrent/MoreExecutors.java#L369
回答3:
have you looked at java.util.concurrent.ThreadPoolExecutor?