Java并发编程实践Callable异步回调FutureFutureTask用法Word格式文档下载.docx
《Java并发编程实践Callable异步回调FutureFutureTask用法Word格式文档下载.docx》由会员分享,可在线阅读,更多相关《Java并发编程实践Callable异步回调FutureFutureTask用法Word格式文档下载.docx(25页珍藏版)》请在冰豆网上搜索。
Future<
/tt>
representstheresultofanasynchronous
*computation.Methodsareprovidedtocheckifthecomputationis
*complete,towaitforitscompletion,andtoretrievetheresultof
*thecomputation.Theresultcanonlyberetrievedusingmethod
*<
get<
whenthecomputationhascompleted,blockingif
*necessaryuntilitisready.Cancellationisperformedbythe
cancel<
method.Additionalmethodsareprovidedto
*determineifthetaskcompletednormallyorwascancelled.Oncea
*computationhascompleted,thecomputationcannotbecancelled.
*Ifyouwouldliketousea<
forthesake
*ofcancellabilitybutnotprovideausableresult,youcan
*declaretypesoftheform{@codeFuture<
?
>
}and
*return<
null<
asaresultoftheunderlyingtask.
p>
b>
SampleUsage<
/b>
(Notethatthefollowingclassesareall
*made-up.)<
pre>
{@code
*interfaceArchiveSearcher{Stringsearch(Stringtarget);
}
*classApp{
*ExecutorServiceexecutor=...
*ArchiveSearchersearcher=...
*voidshowSearch(finalStringtarget)
*throwsInterruptedException{
*Future<
String>
future
*=executor.submit(newCallable<
(){
*publicStringcall(){
*returnsearcher.search(target);
*}});
*displayOtherThings();
//dootherthingswhilesearching
*try{
*displayText(future.get());
//usefuture
*}catch(ExecutionExceptionex){cleanup();
return;
*}
*}}<
/pre>
*The{@linkFutureTask}classisanimplementationof<
that
*implements<
Runnable<
andsomaybeexecutedbyan<
Executor<
.
*Forexample,theaboveconstructionwith<
submit<
couldbereplacedby:
*FutureTask<
future=
*newFutureTask<
(newCallable<
*executor.execute(future);
}<
Memoryconsistencyeffects:
Actionstakenbytheasynchronouscomputation
ahref="
package-summary.html#MemoryVisibility"
<
i>
happen-before<
/i>
<
/a>
*actionsfollowingthecorresponding{@codeFuture.get()}inanotherthread.
*@seeFutureTask
*@seeExecutor
*@since1.5
*@authorDougLea
*@param<
V>
TheresulttypereturnedbythisFuture'
s<
method
publicinterfaceFuture<
{
/**
*Attemptstocancelexecutionofthistask.Thisattemptwill
*failifthetaskhasalreadycompleted,hasalreadybeencancelled,
*orcouldnotbecancelledforsomeotherreason.Ifsuccessful,
*andthistaskhasnotstartedwhen<
iscalled,
*thistaskshouldneverrun.Ifthetaskhasalreadystarted,
*thenthe<
mayInterruptIfRunning<
parameterdetermines
*whetherthethreadexecutingthistaskshouldbeinterruptedin
*anattempttostopthetask.
Afterthismethodreturns,subsequentcallsto{@link#isDone}will
*alwaysreturn<
true<
.Subsequentcallsto{@link#isCancelled}
*willalwaysreturn<
ifthismethodreturned<
*@parammayInterruptIfRunning<
ifthethreadexecutingthis
*taskshouldbeinterrupted;
otherwise,in-progresstasksareallowed
*tocomplete
*@return<
false<
ifthetaskcouldnotbecancelled,
*typicallybecauseithasalreadycompletednormally;
otherwise
booleancancel(booleanmayInterruptIfRunning);
*Returns<
ifthistaskwascancelledbeforeitcompleted
*normally.
booleanisCancelled();
ifthistaskcompleted.
*Completionmaybeduetonormaltermination,anexception,or
*cancellation--inallofthesecases,thismethodwillreturn
ifthistaskcompleted
booleanisDone();
*Waitsifnecessaryforthecomputationtocomplete,andthen
*retrievesitsresult.
*@returnthecomputedresult
*@throwsCancellationExceptionifthecomputationwascancelled
*@throwsExecutionExceptionifthecomputationthrewan
*exception
*@throwsInterruptedExceptionifthecurrentthreadwasinterrupted
*whilewaiting
Vget()throwsInterruptedException,ExecutionException;
*Waitsifnecessaryforatmostthegiventimeforthecomputation
*tocomplete,andthenretrievesitsresult,ifavailable.
*@paramtimeoutthemaximumtimetowait
*@paramunitthetimeunitofthetimeoutargument
*@throwsTimeoutExceptionifthewaittimedout
Vget(longtimeout,TimeUnitunit)
throwsInterruptedException,ExecutionException,TimeoutException;
}
Callable返回Future示例
importjava.util.concurrent.Callable;
importjava.util.concurrent.ExecutorService;
importjava.util.concurrent.Executors;
importjava.util.concurrent.Future;
importjava.util.concurrent.TimeUnit;
*Callable的Future用法
*@package.CallableDemo
*@date2017年4月5日下午2:
53:
18
*@authorpengjunlin
*@comment
*@update
publicclassCallableFuture{
*@paramargs
*@throwsException
*@throwsInterruptedException
publicstaticvoidmain(String[]args)throwsInterruptedException,
Exception{
//TODOAuto-generatedmethodstub
ExecutorServiceexec=Executors.newCachedThreadPool();
//Future是一个接口,该接口用来返回异步的结果。
Future<
st=exec.submit(newTaskCallable());
/*同步结果,并且设置超时时间*/
System.out.println(st.get(10000,TimeUnit.MILLISECONDS));
System.out.println("
finished"
);
classTaskCallableimplementsCallable<
publicStringcall()throwsException{
Thread.sleep(1000);
return"
callstatus=OK"
;
FutureTask
FutureTask实现了java.util.concurrent.RunnableFuture<
接口,实际上实现了Runnable和Future<
两个接口。
FutureTask源码
importjava.util.concurrent.locks.LockSupport;
*Acancellableasynchronouscomputation.Thisclassprovidesabase
*implementationof{@linkFuture},withmethodstostartandcancel
*acomputation,querytoseeifthecomputationiscomplete,and
*retrievetheresultofthecomputation.Theresultcanonlybe
*retrievedwhenthecomputationhascompleted;
the{@codeget}
*methodswillblockifthecomputationhasnotyetcompleted.Once
*thecomputationhascompleted,thecomputationcannotberestarted
*orcancelled(unlessthecomputationisinvokedusing
*{@link#runAndReset}).
A{@codeFutureTask}canbeusedtowrapa{@linkCallable}or
*{@linkRunnable}object.Because{@codeFutureTask}implements
*{@codeRunnable},a{@codeFutureTask}canbesubmittedtoan
*{@linkExecutor}forexecution.
Inadditiontoservingasastandaloneclass,thisclassprovides
*{@codeprotected}functionalitythatmaybeusefulwhencreating
*customizedtaskclasses.
TheresulttypereturnedbythisFutureTask'
s{@codeget}methods
publicclassFutureTask<
implementsRunnableFuture<
/*
*Revisionnotes:
Thisdiffersfrompreviousversionsofthis
*classthatreliedonAbstractQueuedSynchronizer,mainlyto
*avoidsurprisingusersaboutretaininginterruptstatusduring
*cancellationraces.Synccontrolinthecurrentdesignrelies
*ona"
state"
fieldupdatedviaCAStotrackcompletion,along
*withasimpleTreiberstacktoholdwaitingthreads.
*Stylenote:
Asusual,webypassoverheadofusing
*AtomicXFieldUpdatersandinsteaddirectlyuseUnsafeintrinsics.
*Therunstateofthistask,initiallyNEW.Therunstate
*transitionstoaterminalstateonlyinmethodsset,
*setException,andcancel.Duringcompletion,statemaytakeon
*transientvaluesofCOMPLETING(whileoutcomeisbeingset)or
*INTERRUPTING(onlywhileinterruptingtherunnertosatisfya
*cancel(true)).Transitionsfromtheseintermediatetofinal
*statesusecheaperordered/lazywritesbecausevaluesareuniq