Java并发-带返回值的线程池处理流程分析

示例提供

以这段代码为例, 下文讲述带返回值的线程池处理流程。

// 新建一个线程池
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
<
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值