并发基础(一):Executor


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接口,你能够使用单线程、多线程、线程池等来执行具体的任务, 甚至也能够不启用额外的线程,而在调用者所在的线程中完成任务。好比:html

1,在调用者线程中完成任务:java

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

2,多线程,每一个任务一个线程:
android

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经过构造方法传入。this

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接口的子类:spa

AbstractExecutorService线程

ExecutorService设计

ForkJoinPoolcode

ScheduledExecutorServicehtm

ScheduledThreadPoolExecutor

ThreadPoolExecutor

相关文章
相关标签/搜索