An object that executes submitted Runnable tasks. This interface provides a way of decoupling task submission from the mechanics of how each task will be run, including details of thread use, scheduling, etc. An Executor is normally used instead of explicitly creating threads. For example, rather than invoking new Thread(new(RunnableTask())).start() for each of a set of tasks, you might use:
// 一个对象执行提交的任务,此接口提供了一种将任务提交与如何运行每个任务的机制相分离的方法,包含了线程的使用细节,调度等等,Executor 一般用来代替创建线程,
Executor executor = anExecutor;
executor.execute(new RunnableTask1());
executor.execute(new RunnableTask2());
...
However, the Executor interface does not strictly require that execution be asynchronous. In the simplest case, an executor can run the submitted task immediately in the caller's thread:
// 然而,Executor 并不严格的要求执行必须是异步的,一个简单的例子,这面这个执行器会在调用者的线程立即执行class DirectExecutor implements Executor {
publicvoid execute(Runnable r) {
r.run(); //同步的
}
}
More typically, tasks are executed in some thread other than the caller's thread. The executor below spawns a new thread for each task.
//最有代表性的,任务执行的线程不同于调用者的线程, 下面这个执行器就是开启了新的任务的线程。class ThreadPerTaskExecutor implements Executor {
publicvoid execute(Runnable r) {
new Thread(r).start();
}
}
Many Executor implementations impose some sort of limitation on how andwhen tasks are scheduled. The executor below serializes the submission of tasks to a second executor, illustrating a composite executor.
// 很多执行器的实现都加入了排序的限制在任务的调度时,下面这个执行器把任务提交到了第二个执行器,表明是一种复合执行器class SerialExecutor implements Executor {
final Queue<Runnable> tasks = new ArrayDeque<Runnable>();
final Executor executor;
Runnable active;
SerialExecutor(Executor executor) {
this.executor = executor;
}
public synchronized void execute(final Runnable r) {
tasks.offer(new Runnable() {
publicvoid run() {
try {
r.run();
} finally {
scheduleNext();
}
}
});
if (active == null) {
scheduleNext();
}
}
protected synchronized void scheduleNext() {
if ((active = tasks.poll()) != null) {
executor.execute(active);
}
}
}
The Executor implementations provided in this package implement ExecutorService, which is a more extensive interface. The ThreadPoolExecutor class provides an extensible thread pool implementation. The Executors class provides convenient factory methods for these Executors.
Memory consistency effects: Actions in a thread prior to submitting a Runnable object to an Executor happen-before its execution begins, perhaps in another thread.
// 在包中,提供了 Executor 的实现 ExecutorService,ExecutorService提供了更多的实现, ThreadPoolExecutor 这个类就扩展了线程池的实现,Executors类提供了方便的工厂方法给这个执行器