Java 5.0 在 java.util.concurrent 提供了一个新的创建执行线程的方式:Callable 接口。Callable 需要依赖FutureTask ,FutureTask 也可以用作闭锁。
创建线程的四种方式
无返回:
1、实现Runnable接口,重写run();
2、继承Thread类,重写run();
有返回:
3、实现Callable接口,重写call(),利用FutureTask包装Callable,并作为task传入Thread构造函数;
4、利用线程池;
Callable的使用
public class TestCallable {
public static void main(String[] args) {
ThreadDemo td = new ThreadDemo();
//1.执行 Callable 方式,需要 FutureTask 实现类的支持,用于接收运算结果。
FutureTask<Integer> result = new FutureTask<>(td);
new Thread(result).start();
//2.接收线程运算后的结果
try {
Integer sum = result.get(); //FutureTask 可用于 闭锁
System.out.println(sum);
System.out.println("------------------------------------");
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
}
class ThreadDemo implements Callable<Integer>{
@Override
public Integer call() throws Exception {
int sum = 0;
for (int i = 0; i <= 100000; i++) {
sum += i;
}
return sum;
}
}