Executor

Executor 接口中只定义了一个方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public interface Executor {

/**
* Executes the given command at some time in the future. The command
* may execute in a new thread, in a pooled thread, or in the calling
* thread, at the discretion of the {@code Executor} implementation.
*
* @param command the runnable task
* @throws RejectedExecutionException if this task cannot be
* accepted for execution
* @throws NullPointerException if command is null
*/
void execute(Runnable command);
}

execute(Runnable command) 方法负责执行提交的任务,Executor 接口将任务的提交,任务的执行,以及线程使用的细节进行解耦。隐藏了创建线程的操作,甚至可以实现为非异步的方式,即由调用线程来直接执行:

1
2
3
4
5
class DirectExecutor implements Executor {
public void execute(Runnable r) {
r.run();
}
}

但是,通常情况下,是由调用该方法线程以外的线程来执行的,也就是会为每一个 Runnable 任务(命令)创建一个线程来异步执行:

1
2
3
4
5
class ThreadPerTaskExecutor implements Executor {
public void execute(Runnable r) {
new Thread(r).start();
}
}

属于多线程设计模式 Thread-Per-Message(见《图解 Java 多线程设计模式》) 的实现,即为每个请求分配一个新线程,由这个线程来执行处理。

该模式具有以下特点:

  1. 提高方法的响应,缩短延迟时间
  2. 适用于对操作顺序没有要求(即方法的调用顺序不一定和执行顺序一致)
  3. 适用于不需要返回值(execute方法的返回类型为 void

1
2