说明
之前已经学习创建线程的两种方式,
- 1.实现Runnable,
- 2.继承Thread类,
使用Callable接口创建线程与实现Runnable的区别代码演示:
import java.util.concurrent.Callable;
public class CallableDemo implements Callable<Integer> {
@Override
public Integer call() throws Exception {
return null;
}
}
class RunnableDemo implements Runnable {
@Override
public void run() {
}
}
上述代码可以发现,Callable接口从写的方法名为call,并可以有返回值和抛异常。
接收返回值和捕获异常
class Demo {
public static void main(String[] args) {
CallableDemo cd = new CallableDemo();
//用futureTask类来接收
FutureTask<Integer> ft = new FutureTask<>(cd);
new Thread(ft).start();
try {
//get获取返回值
// 注意,get方法是在主线程中,get方法是在FutureTask线程执行结束后才执行的
//因此我们可以得知,FutureTask可用于闭锁
Integer integer = ft.get();
System.out.println(integer);
} catch (InterruptedException | ExecutionException e) {
}
}
}