创建线程之三:实现Callable接口

通过Callable和Future创建线程

  i. 创建Callable接口的实现类,并实现call方法,该call方法将作为线程执行体,并且有返回值,可以抛出异常。

  ii. 创建Callable实现类的实例,使用FutureTask类包装Callable对象,该FuturedTask对象封装了Callable对象的call方法的返回值。

  iii. 使用FutureTask对象作为Thread对象的target,创建并启动新线程。

  iv. 调用FutureTask对象的get方法来获得子线程执行结束后的返回值。

 1 public class TestCallable {
 2     public static void main(String[] args) {
 3         ThreadDemo td = new ThreadDemo();
 4         //1.执行 Callable 方式,需要 FutureTask 实现类的支持,用于接收运算结果。
 5         FutureTask<Integer> result = new FutureTask<>(td);
 6         new Thread(result).start();
 7         //2.接收线程运算后的结果
 8         try {
 9             Integer sum = result.get();  //FutureTask 可用于闭锁
10             System.out.println(sum);
11             System.out.println("------------------------------------");
12         } catch (InterruptedException | ExecutionException e) {
13             e.printStackTrace();
14         }
15     }
16 }
17 class ThreadDemo implements Callable<Integer>{
18     public Integer call() throws Exception {
19         int sum = 0;
20         for (int i = 0; i <= 100000; i++) {
21             sum += i;
22         }    
23         return sum;
24     }    
25 }
 1  //创建一个线程池
 2 ExecutorService pool = Executors.newFixedThreadPool(taskSize);
 3 // 创建多个有返回值的任务
 4 List<Future> list = new ArrayList<Future>(); 
 5 for (int i = 0; i < taskSize; i++) { 
 6     Callable c = new MyCallable(i + " "); 
 7     // 执行任务并获取 Future 对象
 8     Future f = pool.submit(c); 
 9     list.add(f); 
10 } 
11 // 关闭线程池
12 pool.shutdown(); 
13 // 获取所有并发任务的运行结果
14 for (Future f : list) { 
15     // 从 Future 对象上获取任务的返回值,并输出到控制台
16     System.out.println("res:" + f.get().toString()); 
17 } 
posted @ 2019-11-22 12:48  MrHH  阅读(569)  评论(0编辑  收藏  举报