Executor

定义

DOC:

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.

翻译:

执行器就是一个 可以执行 Runnable 任务的对象。
这个接口提供了一种解耦的方式:每个任务的具体定义,和每个任务的执行相分离。(执行:线程的使用,调度等等)。

例子

你可以通过执行器,来执行一堆任务,而不是创建新的线程来执行。

 Executor executor = anExecutor;
 executor.execute(new RunnableTask1());
 executor.execute(new RunnableTask2());

执行器不严格的要求执行的过程是异步的。你可以简单的将任务的执行放在 调用线程中执行。

 class DirectExecutor implements Executor {
   public void execute(Runnable r) {
     r.run();
   
 }}

典型的应用是,执行器中的执行过程在另一个线程中执行。

 class ThreadPerTaskExecutor implements Executor {
   public void execute(Runnable r) {
     new Thread(r).start();
   
 }}

许多执行器的具体实现:关注点在于 任务的调度与执行顺序。
如下:将序列化的执行任务。

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.add(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)