Java並行Executor介面


java.util.concurrent.Executor介面是支援啟動新任務的一個簡單介面。

Executor介面中的方法

序號 方法 描述
1 void execute(Runnable command) 在將來的某個時間執行給定的命令。

範例

以下TestThread程式顯示了如何在基於執行緒的環境中Executor介面的用法。

import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class TestThread {

   public static void main(final String[] arguments) throws InterruptedException {
      Executor executor = Executors.newCachedThreadPool();
      executor.execute(new Task());
      ThreadPoolExecutor pool = (ThreadPoolExecutor)executor;
      pool.shutdown();
   }  

   static class Task implements Runnable {
      public void run() {
         try {
            Long duration = (long) (Math.random() * 5);
            System.out.println("Running Task!");
            TimeUnit.SECONDS.sleep(duration);
            System.out.println("Task Completed");
         } 
         catch (InterruptedException e) {
            e.printStackTrace();
         }
      }
   }
}

執行上面程式碼,得到如下結果 -

Running Task!
Task Completed