简介:
An object that executes submitted {@link Runnable} tasks.
这个接口提供了一种将任务提交与每个任务的运行机制分离的方法。通常使用{@code Executor}而不是显式创建线程。
例如:
不是为每一个任务调度
new Thread(new(RunnableTask())).start()
而是
Executor executor = ... ; executor.execute(new RunnableTask1()); executor.execute(new RunnableTask2());
注意:Executor接口并不严格要求执行是异步的。
在最简单的情况下,执行者可以立即在调用者的线程中运行提交的任务:
class DirectExecutor implements Executor { public void execute(Runnable r) { r.run(); } }
更典型地,任务在调用者线程之外的某个线程中执行。
例如:下面的执行程序为每个任务生成一个新线程:
public class ThreadPerTaskExecutor implements Executor { public void execute(Runnable r) { new Thread(r).start(); } }
许多Executor实现对计划任务的方式和时间施加了某种限制。
下面的执行程序将任务提交序列化到第二个执行程序,演示了一个复合执行器(a composite executor)。
import java.util.ArrayDeque; import java.util.Queue; import java.util.concurrent.Executor; public 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() { public void run() { try { r.run(); } finally { scheduleNext(); } } }); if (active == null) { System.out.println("active == null!"); scheduleNext(); } } protected synchronized void scheduleNext() { if ((active = tasks.poll()) != null) { executor.execute(active); } } }
综合演示:
import java.util.ArrayDeque; import java.util.Queue; import java.util.concurrent.Executor; class DirectExecutor implements Executor { public void execute(Runnable r) { r.run(); } } class ThreadPerTaskExecutor implements Executor { public void execute(Runnable r) { new Thread(r).start(); } } public 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() { public void run() { try { r.run(); } finally { scheduleNext(); } } }); if (active == null) { System.out.println("active == null!"); scheduleNext(); } } protected synchronized void scheduleNext() { if ((active = tasks.poll()) != null) { executor.execute(active); } } } class SerialExecutorMain { public static void main(String[] args) { SerialExecutor serialExecutor = new SerialExecutor(new ThreadPerTaskExecutor()); /**or**/ //SerialExecutor serialExecutor = new SerialExecutor(new DirectExecutor()); for (int i = 0; i < 100; i++) { serialExecutor.execute(new Runnable() { @Override public void run() { System.out.println("Hello!"); } }); } } }