利用Callable&Future创建线程
问题:
之前遇到的的执行任务都是run方法实现的任务,而run方法是没有返回值的,我们并不知道线程什么时候执行结束。
解决途径 :
如果线程执行结束之后能返回一个值,那么我们就知道线程已经之行结束了
public static void main(String[] args) {
ExecutorService threadPool = Executors.newSingleThreadExecutor();
//Callable<T> 泛型的具体类型就是返回值的类型 也决定了Future泛型类型
Future<Integer> future = threadPool.submit(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
System.out.println("任务开始");
Thread.sleep(3000);
System.out.println("任务结束");
return 10;
}
});
int value = 0;
try {
value = future.get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
System.out.println(value);
}