实现Callable接口创建线程

创建执行线程有四种方式:

  • 实现implements接口创建线程
  • 继承Thread类创建线程
  • 实现Callable接口,通过FutureTask包装器来创建线程
  • 使用线程池创建线程

下面介绍通过实现Callable接口来创建线程。

 1 package com.ccfdod.juc;
 2 
 3 import java.util.concurrent.Callable;
 4 import java.util.concurrent.ExecutionException;
 5 import java.util.concurrent.FutureTask;
 6 
 7 /**
 8  * 一、创建执行线程的方式三:实现Callable接口。相较于实现Runnable接口的方式,方法可以有返回值,并且可以抛出异常
 9  * 二、执行Callable方式,需要FutureTask实现类的支持,用于接收运算结果
10  */
11 public class TestCallable {
12     public static void main(String[] args) {
13         ThreadDemo td = new ThreadDemo();
14 
15         // 1.执行Callable方式,需要FutureTask实现类的支持,用于接收运算结果
16         FutureTask<Integer> result = new FutureTask<>(td);
17         new Thread(result).start();
18 
19         // 2.接收线程运算后的结果
20         Integer sum;
21         try {
22             //等所有线程执行完,获取值,因此FutureTask 可用于 闭锁
23             sum = result.get();
24             System.out.println("-----------------------------");
25             System.out.println(sum);
26         } catch (InterruptedException | ExecutionException e) {
27             e.printStackTrace();
28         }
29     }
30 }
31 
32 class ThreadDemo implements Callable<Integer> {
33 
34     @Override
35     public Integer call() throws Exception {
36         int sum = 0;
37         for (int i = 0; i <= 100000; i++) {
38             System.out.println(i);
39             sum += i;
40         }
41         return sum;
42     }
43 }

 

posted @ 2017-02-14 01:37  chunfulandu  阅读(7202)  评论(1编辑  收藏  举报