详解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
相关文章
猜你喜欢
- 64M VPS建站:能否支持高流量网站运行? 2025-06-10
- 64M VPS建站:怎样选择合适的域名和SSL证书? 2025-06-10
- 64M VPS建站:怎样优化以提高网站加载速度? 2025-06-10
- 64M VPS建站:是否适合初学者操作和管理? 2025-06-10
- ASP.NET自助建站系统中的用户注册和登录功能定制方法 2025-06-10
TA的动态
- 2025-07-10 怎样使用阿里云的安全工具进行服务器漏洞扫描和修复?
- 2025-07-10 怎样使用命令行工具优化Linux云服务器的Ping性能?
- 2025-07-10 怎样使用Xshell连接华为云服务器,实现高效远程管理?
- 2025-07-10 怎样利用云服务器D盘搭建稳定、高效的网站托管环境?
- 2025-07-10 怎样使用阿里云的安全组功能来增强服务器防火墙的安全性?
快网idc优惠网
QQ交流群
您的支持,是我们最大的动力!
热门文章
-
2025-06-04 72
-
2025-06-04 64
-
2025-05-25 25
-
2025-05-25 34
-
2025-05-29 91
热门评论

