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);
     }
   }
 }}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容