package com.starit.open.main;import java.util.ArrayList;import java.util.List;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;/** * * @author wenin819 * * Callable 和 Future介面 * Callable是類似於Runnable的介面,實現Callable介面的類和實現Runnable的類都是可被其它線程執行的任務。 * Callable和Runnable有幾點不同: * (1)Callable規定的方法是call(),而Runnable規定的方法是run(). * (2)Callable的任務執行後可傳回值,而Runnable的任務是不能傳回值的。 * (3)call()方法可拋出異常,而run()方法是不能拋出異常的。 * (4)運行Callable任務可拿到一個Future對象, * Future 表示非同步計算的結果。它提供了檢查計算是否完成的方法,以等待計算的完成,並檢索計算的結果。 * 通過Future對象可瞭解任務執行情況,可取消任務的執行,還可擷取任務執行的結果。 * */public class CallableThreadSync implements Runnable{private static final ExecutorService es = Executors.newFixedThreadPool(5);public static class ItemThread implements Callable<Integer> {public int addNum;public ItemThread(int addNum) {this.addNum = addNum;}@Overridepublic Integer call() {try {Thread.sleep(addNum * 1000);} catch (InterruptedException e) {e.printStackTrace();}return addNum * 2;}}public static void main(String[] args) {CallableThreadSync test = new CallableThreadSync();long startTime = System.currentTimeMillis();new Thread(test, "thread1").start();new Thread(test, "thread2").start();long endTime = System.currentTimeMillis();System.out.println("main:用時" + (endTime - startTime) / 1000 + "秒");}public void run() {long startTime = System.currentTimeMillis();List<ItemThread> itemThreads = new ArrayList<CallableThreadSync.ItemThread>(3);ItemThread itemThread = null;for(int i = 0; i < 3; i++) {itemThread = new ItemThread(i + 1);itemThreads.add(itemThread);}List<Future<Integer>> futureList = null;try {futureList = es.invokeAll(itemThreads);} catch (InterruptedException e1) {e1.printStackTrace();}Integer result = 1;for(Future<Integer> future : futureList) {try {result += future.get();} catch (InterruptedException e) {e.printStackTrace();} catch (ExecutionException e) {e.printStackTrace();}}String infoMsg = Thread.currentThread().getName() + ":";long endTime = System.currentTimeMillis();System.out.println(infoMsg + result + "(用時" + (endTime - startTime) / 1000 + "秒)");}@Overrideprotected void finalize() throws Throwable {es.shutdownNow();super.finalize();}}