欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

詳解JDK中ExecutorService與Callable和Future對(duì)線程的支持

 更新時(shí)間:2017年09月22日 10:13:08   作者:莫欺少年窮Java  
這篇文章主要介紹了詳解JDK中ExecutorService與Callable和Future對(duì)線程的支持的相關(guān)資料,希望通過(guò)本文能幫助到大家,需要的朋友可以參考下

詳解JDK中ExecutorService與Callable和Future對(duì)線程的支持

1、代碼背景:

    假如有Thread1、Thread2、Thread3、Thread4四條線程分別統(tǒng)計(jì)C、D、E、F四個(gè)盤的大小,所有線程都統(tǒng)計(jì)完畢交給Thread5線程去做匯總,應(yīng)當(dāng)如何實(shí)現(xiàn)?

2、代碼:

    統(tǒng)計(jì)“盤子”大小的代碼,此處實(shí)現(xiàn)jdk中的Callable接口,

package com.wang.test.concurrent; 
 
import java.util.concurrent.Callable; 
 
public class Task1 implements Callable<Integer> { 
 
  private int x; 
  private int y; 
   
  public Task1(int x, int y) { 
    this.x = x; 
    this.y = y; 
  } 
 
  @Override 
  public Integer call() throws Exception { 
    return x*y; 
  } 
 
} 

    統(tǒng)計(jì)匯總的代碼,也是實(shí)現(xiàn)jdk中的Callable接口,

package com.wang.test.concurrent; 
 
import java.util.concurrent.Callable; 
 
public class Task2 implements Callable<Integer> { 
 
  private int x; 
  private int y; 
  private int q; 
  private int w; 
   
  public Task2(int x, int y, int q, int w) { 
    this.x = x; 
    this.y = y; 
    this.q = q; 
    this.w = w; 
  } 
 
  @Override 
  public Integer call() throws Exception { 
    return x + y + q + w; 
  } 
 
} 

     客戶端:使用JDK中Executors.newFixedThreadPool方法創(chuàng)建ExecutorService,ExecutorService的submit方法接收Callable接口的實(shí)現(xiàn),JDK內(nèi)部將弄成線程處理,使用Future接收submit方法的返回值,當(dāng)future調(diào)用get方法時(shí),如果線程還沒(méi)有執(zhí)行完,程序阻塞在這里,知道線程執(zhí)行完。

package com.wang.test.concurrent; 
 
import java.util.concurrent.ExecutorService; 
import java.util.concurrent.Executors; 
import java.util.concurrent.Future; 
 
public class Client { 
 
  public static void main(String[] args) throws Exception { 
    ExecutorService pool = Executors.newFixedThreadPool(4); 
 
    Task1 t1 = new Task1(1,2); 
    Task1 t2 = new Task1(23,34); 
    Task1 t3 = new Task1(23,456); 
    Task1 t4 = new Task1(3,33); 
    Future<Integer> f1 = pool.submit(t1); 
    Future<Integer> f2 = pool.submit(t2); 
    Future<Integer> f3 = pool.submit(t3); 
    Future<Integer> f4 = pool.submit(t4); 
     
    //Future調(diào)用get方法時(shí),如果線程還沒(méi)有執(zhí)行完,程序阻塞在這里 
    Task2 t5 = new Task2(f1.get(), f2.get(), f3.get(), f4.get()); 
    Future<Integer> f5 = pool.submit(t5); 
     
    System.out.println(f5.get()); 
     
    pool.shutdown(); 
  } 
} 

如有疑問(wèn)請(qǐng)留言或者到本站社區(qū)交流討論,感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!

相關(guān)文章

最新評(píng)論