调用FutureTask对象的get方法,其返回值为call方法的返回值

[复制链接]
查看11 | 回复1 | 2021-1-27 06:19:13 | 显示全部楼层 |阅读模式
1.想写点什么,就随便写写吧。
packageimportant;
importjava.util.concurrent.Callable;
importjava.util.concurrent.ExecutionException;
importjava.util.concurrent.FutureTask;
publicclassTextt{
publicstaticvoidmain(String[]args)throwsInterruptedException,ExecutionException{
FutureTask[I]task=newFutureTask(newCallable[I](){
@Override
publicIntegercall()throwsException{
intsum=2;
returnsum;
}
});
Threadthread=newThread(task);
thread.start();
//get方法的返回值是什么呢?
System.out.println(task.get());
}
}
2.下面对get方法的返回值简要分析,进入FutureTask源码
get方法的返回值为report方法返回值
publicVget()throwsInterruptedException,ExecutionException{
ints=state;
if(s
report方法的返回值为outcome,是futuretask的一个属性
//outcome属性
/**Theresulttoreturnorexceptiontothrowfromget()*/
privateObjectoutcome;//non-volatile,protectedbystatereads/writes
//report方法
privateVreport(ints)throwsExecutionException{
Objectx=outcome;
if(s==NORMAL)
return(V)x;
if(s>=CANCELLED)
thrownewCancellationException();
thrownewExecutionException((Throwable)x);
}

//run方法里调用callable的实现类的方法call,返回值赋给result,调用set方法,将result进行传值
publicvoidrun(){
if(state!=NEW||
!UNSAFE.compareAndSwapObject(this,runnerOffset,
null,Thread.currentThread()))
return;
try{
Callablec=callable;
if(c!=null&&state==NEW){
Vresult;
booleanran;
try{
result=c.call();
ran=true;
}catch(Throwableex){
result=null;
ran=false;
setException(ex);
}
if(ran)
set(result);
}
}finally{
//runnermustbenon-nulluntilstateissettledto
//preventconcurrentcallstorun()
runner=null;
//statemustbere-readafternullingrunnertoprevent
//leakedinterrupts
ints=state;
if(s>=INTERRUPTING)
handlePossibleCancellationInterrupt(s);
}
}
//set方法将result的值赋给outcome
protectedvoidset(Vv){
if(UNSAFE.compareAndSwapInt(this,stateOffset,NEW,COMPLETING)){
outcome=v;
UNSAFE.putOrderedInt(this,stateOffset,NORMAL);//finalstate
finishCompletion();
}
}
综上,call方法的返回值给了outcome,outcome将值作为get方法的返回值,也就是call方法的返回值就是get方法得当返回值。
分 -->
回复

使用道具 举报

千问 | 2021-1-27 06:19:13 | 显示全部楼层
没必要写着复杂
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

主题

0

回帖

4882万

积分

论坛元老

Rank: 8Rank: 8

积分
48824836
热门排行