jdk中有一种线程池提交任务时,会直接使用调用者线程来进行执行任务,例如如下代码:
public static void main(String[] args) {
Executor executor = MoreExecutors.directExecutor();
executor.execute(() -> System.out.println("Thread:" + Thread.currentThread().getName()));
System.out.println("Thread:" + Thread.currentThread().getName());
}
结果
Thread:main
Thread:main
Process finished with exit code 0
关于DirectExcutor的解释如下:
/**
* Returns an {@link Executor} that runs each task in the thread that invokes
* {@link Executor#execute execute}, as in {@link CallerRunsPolicy}.
*
* <p>This instance is equivalent to: <pre> {@code
* final class DirectExecutor implements Executor {
* public void execute(Runnable r) {
* r.run();
* }
* }}</pre>
*
* <p>This should be preferred to {@link #newDirectExecutorService()} because implementing the
* {@link ExecutorService} subinterface necessitates significant performance overhead.
*
* @since 18.0
*/
public static Executor directExecutor() {
return DirectExecutor.INSTANCE;
}
/** See {@link #directExecutor} for behavioral notes. */
private enum DirectExecutor implements Executor {
INSTANCE;
@Override
public void execute(Runnable command) {
command.run();
}
@Override
public String toString() {
return "MoreExecutors.directExecutor()";
}
}
可以看到当执行execute(Runnable command)时,直接调用的command.run()方法执行。所以说DirectExecutor是个伪线程池,这里源码里面是通过枚举来创建单例模式的。