示例提供
以这段代码为例, 下文讲述带返回值的线程池处理流程。
// 新建一个线程池
private ExecutorService executor = new ThreadPoolExecutor(20, 50, 2, TimeUnit.SECONDS,
new LinkedBlockingQueue<Runnable>(50), new ThreadPoolExecutor.CallerRunsPolicy());
Future<Boolean> future = executor.submit(new Callable<Boolean>() {
public Boolean call() throws Exception {
// ...
return true;
};
});
// 获取结果
Boolean res = future.get(timeout, TimeUnit.MILLISECONDS);
先说结论
**返回值存储在FutureTask类的内部变量outcome 中,设置返回值由FutureTask#run方法处理,获取返回值由FutureTask#get方法处理 **。
下面是FutureTask类一些重要的变量以及构造函数
/** The underlying callable; nulled out after running */
private Callable<V> callable;
/** The result to return or exception to throw from get() */
private Object outcome; // non-volatile, protected by state reads/writes
/** The thread running the callable; CASed during run() */
private volatile Thread runner;
/**
* 参数为callable
*/
public FutureTask(Callable<V> callable) {
if (callable == null)
throw new NullPointerException();
this.callable = callable;
this.state = NEW; // ensure visibility of callable
<