Executor 的定义
public interface Executor {
void execute(Runnable command);
}
解释
java.util.concurrent包下对于Executor的一个扩展性比较好的实现是ExecutorService。ThreadPoolExecutor类提供了一个可扩展的线程池的实现,其间接实现了Executor。Executors类提供了许多便利的工厂方法用于创建上述Executor实现类的对象。
实现类
许多Executor的实现类会新增一些关于如何以及何时调度任务的限制。下面将给出一个例子,该例子将提交的任务按照顺序依次放到第二个executor中予以调度执行,这体现了一种组合的executor。
设计得十分巧妙,值得借鉴,主要就是利用一个队列进行保存提交的任务,然后每个提交过来的任务,对它进行包装,使得其执行完成后,自动调度队列中的下一个线程任务使之运行,如此妙哉!佩服!
class SerialExecutor implements Executor {
final Queue<Runnable> tasks = new ArrayDeque<Runnable>();
final Executor executor;
Runnable active;
SerialExecutor(Excecutor 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();
}
}
public synchronized void scheduleNext() {
if ((active == tasks.poll()) != null)
executor.execute(active);
}
}
}