Callable與Future

接着上一篇繼續併發包的學習,本篇說明的是Callable和Future,它倆頗有意思的,一個產生結果,一個拿到結果。java

        Callable接口相似於Runnable,從名字就能夠看出來了,可是Runnable不會返回結果,而且沒法拋出返回結果的異常,而Callable功能更強大一些,被線程執行後,能夠返回值,這個返回值能夠被Future拿到,也就是說,Future能夠拿到異步執行任務的返回值,下面來看一個簡單的例子:編程

public class CallableAndFuture {  
    public static void main(String[] args) {  
        Callable<Integer> callable = new Callable<Integer>() {  
            public Integer call() throws Exception {  
                return new Random().nextInt(100);  
            }  
        };  
        FutureTask<Integer> future = new FutureTask<Integer>(callable);  
        new Thread(future).start();  
        try {  
            Thread.sleep(5000);// 可能作一些事情  
            System.out.println(future.get());  
        } catch (InterruptedException e) {  
            e.printStackTrace();  
        } catch (ExecutionException e) {  
            e.printStackTrace();  
        }  
    }  
}

 FutureTask實現了兩個接口,Runnable和Future,因此它既能夠做爲Runnable被線程執行,又能夠做爲Future獲得Callable的返回值,那麼這個組合的使用有什麼好處呢?假設有一個很耗時的返回值須要計算,而且這個返回值不是馬上須要的話,那麼就可使用這個組合,用另外一個線程去計算返回值,而當前線程在使用這個返回值以前能夠作其它的操做,等到須要這個返回值時,再經過Future獲得,豈不美哉!這裏有一個Future模式的介紹:http://openhome.cc/Gossip/DesignPattern/FuturePattern.htm
併發

        下面來看另外一種方式使用Callable和Future,經過ExecutorService的submit方法執行Callable,並返回Future,代碼以下:dom

public class CallableAndFuture {  
    public static void main(String[] args) {  
        ExecutorService threadPool = Executors.newSingleThreadExecutor();  
        Future<Integer> future = threadPool.submit(new Callable<Integer>() {  
            public Integer call() throws Exception {  
                return new Random().nextInt(100);  
            }  
        });  
        try {  
            Thread.sleep(5000);// 可能作一些事情  
            System.out.println(future.get());  
        } catch (InterruptedException e) {  
            e.printStackTrace();  
        } catch (ExecutionException e) {  
            e.printStackTrace();  
        }  
    }  
}

  代碼是否是簡化了不少,ExecutorService繼承自Executor,它的目的是爲咱們管理Thread對象,從而簡化併發編程,Executor使咱們無需顯示的去管理線程的生命週期,是JDK 5以後啓動任務的首選方式。
異步

        執行多個帶返回值的任務,並取得多個返回值,代碼以下:學習

public class CallableAndFuture {  
    public static void main(String[] args) {  
        ExecutorService threadPool = Executors.newCachedThreadPool();  
        CompletionService<Integer> cs = new ExecutorCompletionService<Integer>(threadPool);  
        for(int i = 1; i < 5; i++) {  
            final int taskID = i;  
            cs.submit(new Callable<Integer>() {  
                public Integer call() throws Exception {  
                    return taskID;  
                }  
            });  
        }  
        // 可能作一些事情  
        for(int i = 1; i < 5; i++) {  
            try {  
                System.out.println(cs.take().get());  
            } catch (InterruptedException e) {  
                e.printStackTrace();  
            } catch (ExecutionException e) {  
                e.printStackTrace();  
            }  
        }  
    }  
}

其實也能夠不使用CompletionService,能夠先建立一個裝Future類型的集合,用Executor提交的任務返回值添加到集合中,最後遍歷集合取出數據,代碼略。spa

相關文章
相關標籤/搜索