向线程池提交Callable任务,会创建一个新线程(执行任务的线程)去执行这个Callable任务,但是通过Future#get获取任务的执行结果是在提交任务的调用者线程中。
问题一:调用者线程如何获取执行任务的线程的结果?
在JDK中,有2种类型的任务,Runnable和Callable,但是具体到线程池执行任务的java.util.concurrent.ThreadPoolExecutor#execute(Runnable)
方法,它只接收Runnable任务。
问题二:Callable任务是提交给线程池后是如何执行的呢?
Callable 任务是怎么运行的?
import java.util.concurrent.*;
public class FutureTest {
public static void main(String[] args) {
Callable<Integer> callable = new Callable<Integer>() {
@Override
public Integer call() throws Exception {
//sleep 是为了调试方便
TimeUnit.SECONDS.sleep(4);
return 3;
}
};
//创建一个 ThreadPoolExecutor 对象
ExecutorService executorService = Executors.newFixedThreadPool(1);
Future<Integer> future = executorService.submit(callable);
try {
Integer i = future.get();
System.out.println(i);
} catch (Exception e) {
System.out.println(e);
}
}
}
Future<Integer> future = executorService.submit(callable);
//java.util.concurrent.AbstractExecutorService#submit(java.util.concurrent.Callable<T>)
public <T> Future<T> submit(Callable<T> task) {
if (task == null) throw new NullPointerException();
//FutureTask其实是个RunnableFuture, RunnableFuture其实是个Runnable
//重点是: Runnable#run方法的执行,其实就是 FutureTask#run方法的执行!!!
RunnableFuture<T> ftask = newTaskFor(task);
//java.util.concurrent.ThreadPoolExecutor#execute
execute(ftask);
return ftask;
}
//需要获取资料的朋友请加Q君样:290194256*
RunnableFuture<T> ftask = newTaskFor(task);
//java.util.concurrent.AbstractExecutorService#newTaskFor(java.util.concurrent.Callable<T>)
protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {
return new FutureTask<T>(callable);
}
当submit一个Callable任务时,会生成一个RunnableFuture接口对象,默认情况下 RunnableFuture对象是一个FutureTask对象。看java.util.concurrent.AbstractExecutorSe