小男孩‘自慰网亚洲一区二区,亚洲一级在线播放毛片,亚洲中文字幕av每天更新,黄aⅴ永久免费无码,91成人午夜在线精品,色网站免费在线观看,亚洲欧洲wwwww在线观看

分享

Java線程(六):Callable和Future

 AIyeah 2013-07-14
 Callable接口類似于Runnable,從名字就可以看出來了,但是Runnable不會返回結(jié)果,并且無法拋出返回結(jié)果的異常,而Callable功能更強(qiáng)大一些,被線程執(zhí)行后,可以返回值,這個(gè)返回值可以被Future拿到,也就是說,F(xiàn)uture可以拿到異步執(zhí)行任務(wù)的返回值,下面來看一個(gè)簡單的例子:

  1. public class CallableAndFuture {  
  2.     public static void main(String[] args) {  
  3.         Callable<Integer> callable = new Callable<Integer>() {  
  4.             public Integer call() throws Exception {  
  5.                 return new Random().nextInt(100);  
  6.             }  
  7.         };  
  8.         FutureTask<Integer> future = new FutureTask<Integer>(callable);  
  9.         new Thread(future).start();  
  10.         try {  
  11.             Thread.sleep(5000);// 可能做一些事情  
  12.             System.out.println(future.get());  
  13.         } catch (InterruptedException e) {  
  14.             e.printStackTrace();  
  15.         } catch (ExecutionException e) {  
  16.             e.printStackTrace();  
  17.         }  
  18.     }  
  19. }  
        FutureTask實(shí)現(xiàn)了兩個(gè)接口,Runnable和Future,所以它既可以作為Runnable被線程執(zhí)行,又可以作為Future得到Callable的返回值,那么這個(gè)組合的使用有什么好處呢?假設(shè)有一個(gè)很耗時(shí)的返回值需要計(jì)算,并且這個(gè)返回值不是立刻需要的話,那么就可以使用這個(gè)組合,用另一個(gè)線程去計(jì)算返回值,而當(dāng)前線程在使用這個(gè)返回值之前可以做其它的操作,等到需要這個(gè)返回值時(shí),再通過Future得到,豈不美哉!這里有一個(gè)Future模式的介紹:http://caterpillar./Gossip/DesignPattern/FuturePattern.htm。

        下面來看另一種方式使用Callable和Future,通過ExecutorService的submit方法執(zhí)行Callable,并返回Future,代碼如下:

  1. public class CallableAndFuture {  
  2.     public static void main(String[] args) {  
  3.         ExecutorService threadPool = Executors.newSingleThreadExecutor();  
  4.         Future<Integer> future = threadPool.submit(new Callable<Integer>() {  
  5.             public Integer call() throws Exception {  
  6.                 return new Random().nextInt(100);  
  7.             }  
  8.         });  
  9.         try {  
  10.             Thread.sleep(5000);// 可能做一些事情  
  11.             System.out.println(future.get());  
  12.         } catch (InterruptedException e) {  
  13.             e.printStackTrace();  
  14.         } catch (ExecutionException e) {  
  15.             e.printStackTrace();  
  16.         }  
  17.     }  
  18. }  
        代碼是不是簡化了很多,ExecutorService繼承自Executor,它的目的是為我們管理Thread對象,從而簡化并發(fā)編程,Executor使我們無需顯示的去管理線程的生命周期,是JDK 5之后啟動(dòng)任務(wù)的首選方式。

        執(zhí)行多個(gè)帶返回值的任務(wù),并取得多個(gè)返回值,代碼如下:

  1. public class CallableAndFuture {  
  2.     public static void main(String[] args) {  
  3.         ExecutorService threadPool = Executors.newCachedThreadPool();  
  4.         CompletionService<Integer> cs = new ExecutorCompletionService<Integer>(threadPool);  
  5.         for(int i = 1; i < 5; i ) {  
  6.             final int taskID = i;  
  7.             cs.submit(new Callable<Integer>() {  
  8.                 public Integer call() throws Exception {  
  9.                     return taskID;  
  10.                 }  
  11.             });  
  12.         }  
  13.         // 可能做一些事情  
  14.         for(int i = 1; i < 5; i ) {  
  15.             try {  
  16.                 System.out.println(cs.take().get());  
  17.             } catch (InterruptedException e) {  
  18.                 e.printStackTrace();  
  19.             } catch (ExecutionException e) {  
  20.                 e.printStackTrace();  
  21.             }  
  22.         }  
  23.     }  
  24. }        

        其實(shí)也可以不使用CompletionService,可以先創(chuàng)建一個(gè)裝Future類型的集合,用Executor提交的任務(wù)返回值添加到集合中,最后便利集合取出數(shù)據(jù),代碼略。

    本站是提供個(gè)人知識管理的網(wǎng)絡(luò)存儲空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點(diǎn)。請注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購買等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點(diǎn)擊一鍵舉報(bào)。
    轉(zhuǎn)藏 分享 獻(xiàn)花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多