详解JDK中ExecutorService与Callable和Future对线程的支持

2025-05-29 0 40

详解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方法创建ExecutorServiceExecutorService的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

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 详解JDK中ExecutorService与Callable和Future对线程的支持 https://www.kuaiidc.com/114931.html

相关文章

发表评论
暂无评论