import java.util.concurrent.Callable;import java.util.concurrent.ExecutionException;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Future;import java.util.concurrent.ScheduledExecutorService;import java.util.concurrent.TimeUnit;/** * 新的任務執行架構。 * 在Java 5.0之前啟動一個任務是通過調用Thread類的start()方法來實現的, * 任務的提於交和執行是同時進行的,如果你想對任務的執行進行調度, * 或是控制同時執行的線程數量就需要額外編寫代碼來完成。 * 5.0裡提供了一個新的任務執行架構使你可以輕鬆地調度和控制任務的執行, * 並且可以建立一個類似資料庫連接池的線程池來執行任務。 * 這個架構主要有三個介面和其相應的具體類組成。 * 這三個介面是Executor, ExecutorService和ScheduledExecutorService。 * (1)Executor介面:是用來執行Runnable任務的,它只定義一個方法: * execute(Runnable command):執行Ruannable類型的任務 * (2)ExecutorService:繼承了Executor的方法,並提供了執行Callable任務和中止任務執行的服務, * 其定義的方法主要有: * submit(task):可用來提交Callable或Runnable任務,並返回代表此任務的Future對象 * invokeAll(collection of tasks):批處理任務集合,並返回一個代表這些任務的Future對象集合 * shutdown():在完成已提交的任務後關閉服務,不再接受新任務 * shutdownNow():停止所有正在執行的任務並關閉服務。 * isTerminated():測試是否所有任務都執行完畢了。 * isShutdown():測試是否該ExecutorService已被關閉 * (3)ScheduledExecutorService:繼承ExecutorService,提供了按時間安排執行任務的功能、 * schedule(task, initDelay): 安排所提交的Callable或Runnable任務在initDelay指定的時間後執行。 * scheduleAtFixedRate():安排所提交的Runnable任務按指定的間隔重複執行 * scheduleWithFixedDelay():安排所提交的Runnable任務在每次執行完後,等待delay所指定的時間後重複執行。 * * 通過Executors類來獲得各種服務物件。 * callable(Runnable task): 將Runnable的任務轉化成Callable的任務 * newSingleThreadExecutor: 產生一個ExecutorService對象,這個對象只有一個線程可用來執行任務,若任務多於一個,任務將按先後順序執行。 * newCachedThreadPool(): 產生一個ExecutorService對象,這個對象帶有一個線程池,線程池的大小會根據需要調整,線程執行完任務後返回線程池,供執行下一次任務使用。 * newFixedThreadPool(int poolSize):產生一個ExecutorService對象,這個對象帶有一個大小為poolSize的線程池,若任務數量大於poolSize,任務會被放在一個queue裡順序執行。 * newSingleThreadScheduledExecutor:產生一個ScheduledExecutorService對象,這個對象的線程池大小為1,若任務多於一個,任務將按先後順序執行。 * newScheduledThreadPool(int poolSize): 產生一個ScheduledExecutorService對象,這個對象的線程池大小為poolSize,若任務數量大於poolSize,任務會在一個queue裡等待執行 */public class ExecuteArch {/** * 該線程輸出一行字串 */public static class MyThread implements Runnable {public void run() {System.out.println("Task repeating. " + System.currentTimeMillis());try {Thread.sleep(1000);} catch (InterruptedException e) {System.out.println("Task interrupted. "+ System.currentTimeMillis());}}}/** * 該Callable結束另一個任務 */public static class MyCallable implements Callable {private Future future;public MyCallable(Future future) {this.future = future;}public String call() {System.out.println("To cancell Task..."+ +System.currentTimeMillis());this.future.cancel(true);return "Task cancelled!";}}/** * @param args * @throws ExecutionException * @throws InterruptedException */public static void main(String[] args) throws InterruptedException,ExecutionException {// 產生一個ExecutorService對象,這個對象帶有一個線程池,線程池的大小會根據需要調整,// 線程執行完任務後返回線程池,供執行下一次任務使用。ExecutorService cachedService = Executors.newCachedThreadPool();Future myThreadFuture = cachedService.submit(new MyThread());Future myCallableFuture = cachedService.submit(new MyCallable(myThreadFuture));System.out.println(myCallableFuture.get());System.out.println("-----------------");// 將Runnable任務轉換成Callable任務Callable myThreadCallable = Executors.callable(new MyThread());Future myThreadCallableFuture = cachedService.submit(myThreadCallable);// 對於Runnable任務,轉換成Callable任務後,也沒有傳回值System.out.println(myThreadCallableFuture.get());cachedService.shutdownNow();System.out.println("-----------------");// 產生一個ExecutorService對象,這個對象帶有一個大小為poolSize的線程池,// 若任務數量大於poolSize,任務會被放在一個queue裡順序執行ExecutorService fixedService = Executors.newFixedThreadPool(2);fixedService.submit(new MyThread());fixedService.submit(new MyThread());// 由於線程池大小為2,所以後面的任務必須等待前面的任務執行完後才能被執行。myThreadFuture = fixedService.submit(new MyThread());myCallableFuture = fixedService.submit(new MyCallable(myThreadFuture));System.out.println(myCallableFuture.get());fixedService.shutdownNow();System.out.println("-----------------");// 產生一個ScheduledExecutorService對象,這個對象的線程池大小為poolSize,// 若任務數量大於poolSize,任務會在一個queue裡等待執行ScheduledExecutorService fixedScheduledService = Executors.newScheduledThreadPool(2);// 建立任務1MyThread task1 = new MyThread();// 使用任務執行服務立即執行任務1,而且此後每隔2秒執行一次任務1。myThreadFuture = fixedScheduledService.scheduleAtFixedRate(task1, 0, 2,TimeUnit.SECONDS);// 建立任務2MyCallable task2 = new MyCallable(myThreadFuture);// 使用任務執行服務等待5秒後執行任務2,執行它後會將任務1關閉。myCallableFuture = fixedScheduledService.schedule(task2, 5,TimeUnit.SECONDS);System.out.println(myCallableFuture.get());fixedScheduledService.shutdownNow();}}