利用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);
}
使用Callable与Future
本文介绍如何使用Callable和Future来创建可以返回值的线程,并通过示例代码展示如何得知线程何时结束及获取其返回值。

被折叠的 条评论
为什么被折叠?



