码迷,mamicode.com
首页 > 编程语言 > 详细

02027_线程池练习:返回两个数相加的结果

时间:2017-12-24 22:46:47      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:gpo   row   实现   turn   alt   body   调用   ima   future   

1、要求:通过线程池中的线程对象,使用Callable接口完成两个数求和操作。

2、代码实现:

  (1)Callable接口实现类

 1 import java.util.concurrent.Callable;
 2 
 3 public class MyCallable implements Callable<Integer> {
 4     // 成员变量
 5     int x = 5;
 6     int y = 3;
 7 
 8     // 构造方法
 9     public MyCallable() {
10     }
11 
12     public MyCallable(int x, int y) {
13         this.x = x;
14         this.y = y;
15     }
16 
17     @Override
18     public Integer call() throws Exception {
19         return x + y;
20     }
21 }

  (2)测试类

 1 import java.util.concurrent.ExecutionException;
 2 import java.util.concurrent.ExecutorService;
 3 import java.util.concurrent.Executors;
 4 import java.util.concurrent.Future;
 5 
 6 public class ThreadPoolDemo {
 7     public static void main(String[] args) throws InterruptedException,
 8             ExecutionException {
 9         // 创建线程池对象
10         ExecutorService threadPool = Executors.newFixedThreadPool(2);
11 
12         // 创建一个Callable接口子类对象
13         // MyCallable c = new MyCallable();
14         MyCallable c = new MyCallable(100, 200);
15         MyCallable c2 = new MyCallable(10, 20);
16 
17         // 获取线程池中的线程,调用Callable接口子类对象中的call()方法, 完成求和操作
18         // <Integer> Future<Integer> submit(Callable<Integer> task)
19         // Future 结果对象
20         Future<Integer> result = threadPool.submit(c);
21         // 此 Future 的 get 方法所返回的结果类型
22         Integer sum = result.get();
23         System.out.println("sum=" + sum);
24 
25         // 再演示
26         result = threadPool.submit(c2);
27         sum = result.get();
28         System.out.println("sum=" + sum);
29         // 关闭线程池(可以不关闭)
30 
31     }
32 }

3、运行结果:

  技术分享图片

 

  

l  Callable接口实现类

 

02027_线程池练习:返回两个数相加的结果

标签:gpo   row   实现   turn   alt   body   调用   ima   future   

原文地址:http://www.cnblogs.com/gzdlh/p/8099279.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!