併發基礎(一):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

相關文章
相關標籤/搜索