詳解JDK中ExecutorService與Callable和Future對(duì)線程的支持
成都創(chuàng)新互聯(lián)長(zhǎng)期為上1000+客戶提供的網(wǎng)站建設(shè)服務(wù),團(tuán)隊(duì)從業(yè)經(jīng)驗(yàn)10年,關(guān)注不同地域、不同群體,并針對(duì)不同對(duì)象提供差異化的產(chǎn)品和服務(wù);打造開(kāi)放共贏平臺(tái),與合作伙伴共同營(yíng)造健康的互聯(lián)網(wǎng)生態(tài)環(huán)境。為彭澤企業(yè)提供專業(yè)的成都網(wǎng)站制作、成都網(wǎng)站設(shè)計(jì),彭澤網(wǎng)站改版等技術(shù)服務(wù)。擁有十載豐富建站經(jīng)驗(yàn)和眾多成功案例,為您定制開(kāi)發(fā)。
1、代碼背景:
假如有Thread1、Thread2、Thread3、Thread4四條線程分別統(tǒng)計(jì)C、D、E、F四個(gè)盤(pán)的大小,所有線程都統(tǒng)計(jì)完畢交給Thread5線程去做匯總,應(yīng)當(dāng)如何實(shí)現(xiàn)?
2、代碼:
統(tǒng)計(jì)“盤(pán)子”大小的代碼,此處實(shí)現(xiàn)jdk中的Callable接口,
package com.wang.test.concurrent; import java.util.concurrent.Callable; public class Task1 implements Callable{ 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{ 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); Futuref1 = pool.submit(t1); Future f2 = pool.submit(t2); Future f3 = pool.submit(t3); Future 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 f5 = pool.submit(t5); System.out.println(f5.get()); pool.shutdown(); } }
如有疑問(wèn)請(qǐng)留言或者到本站社區(qū)交流討論,感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!