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. */ void execute(Runnable command);}
Executor是一个接口, 这样的设计用来执行Runnable任务,把任务提交过程与具体的执行机制解耦开。有了Executor你不必再费心如何控制任务的执行,包括线程、调度等。当然这些都依赖于如何实现Executor接口,你可以使用单线程、多线程、线程池等来执行具体的任务, 甚至也可以不启用额外的线程,而在调用者所在的线程中完成任务。比如:
1,在调用者线程中完成任务:
class DirectExecutor implements Executor { public void execute(Runnable r) { r.run(); }}
2,多线程,每个任务一个线程:
class ThreadPerTaskExecutor implements Executor { public void execute(Runnable r) { new Thread(r).start(); }}
3, Many Executor
implementations impose some sort of limitation on how and when tasks are scheduled. The executor below serializes the submission of tasks to a second executor, illustrating a composite executor.
许多Executor的实现会对任务执行的时机和调度方法做一些定制。下面的SerialExecutor在任务的调度上做了定制, 使所有提交给serial executor的任务串行的执行, 而任务的具体执行过程交给另一个 executor 负责,改executor通过构造方法传入。
class SerialExecutor implements Executor { final Queue tasks = new ArrayDeque(); final Executor executor; Runnable active; SerialExecutor(Executor executor) { this.executor = executor; public synchronized void execute(final Runnable r) { tasks.offer(new Runnable() { public void run() { try { r.run(); } finally { scheduleNext(); } } }); if (active == null) { scheduleNext(); } } protected synchronized void scheduleNext() { if ((active = tasks.poll()) != null) { executor.execute(active); } } }}
实现了Executor接口的子类:
,
,
,
,
,