詳解JDK中ExecutorService與Callable和Future對線程的支持
1、代碼背景:
假如有Thread1、Thread2、Thread3、Thread4四條線程分別統計C、D、E、F四個盤的大小,所有線程都統計完畢交給Thread5線程去做匯總,應當如何實現?
2、代碼:
統計“盤子”大小的代碼,此處實現jdk中的Callable接口,
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
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; } } |
統計匯總的代碼,也是實現jdk中的Callable接口,
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
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方法創建ExecutorService,ExecutorService的submit方法接收Callable接口的實現,JDK內部將弄成線程處理,使用Future接收submit方法的返回值,當future調用get方法時,如果線程還沒有執行完,程序阻塞在這里,知道線程執行完。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
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調用get方法時,如果線程還沒有執行完,程序阻塞在這里 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(); } } |
如有疑問請留言或者到本站社區交流討論,感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
原文鏈接:http://hejiawangjava.iteye.com/blog/2393827