Runnable和Callable的主要区别
Callable源码解释如下:
* <p>The {@code Callable} interface is similar to {@link
* java.lang.Runnable}, in that both are designed for classes whose
* instances are potentially executed by another thread. A
* {@code Runnable}, however, does not return a result and cannot
* throw a checked exception.
即Callable具有返回值且可以捕捉异常,而Runnable不可以。
Future是一个存储异步任务产生的结果的接口,正常用法就是将一个Callable任务扔给线程池执行(扔给线程池之后就继续往下执行了),然后异步等待得到返回结果。简单Demo如下:
private static void useDemo() throws InterruptedException, ExecutionException {
ExecutorService executorService= Executors.newSingleThreadExecutor();
Callable<Integer> callable= () -> {
int sum=0;
for (int i = 0; i < 1000000; i++) {
sum+=i;
}
TimeUnit.SECONDS.sleep(2);
return sum;
};
// 把future任务提交给线程池执行,但是返回结果是异步的
Future<Integer> submit = executorService.submit(callable);
System.out.println(submit.isDone());
System.out.println("阻塞开始");
// 如果一直得不到返回结果,则一直在阻塞
System.out.println(submit.get());
System.out.println("阻塞结束");
executorService.shutdown();
}
FutureTask是Future的唯一实现类,同时也实现了Runnable接口,也可以直接将FutureTask直接提交到线程池执行。
简单总结如下:
1.Callable=Runnable+返回值
2.Future: 存储异步任务产生的结果
3.FutureTask:既是Future又是Runnable
网友评论