Java并发编程实践Callable异步回调FutureFutureTask用法Word格式文档下载.docx

上传人:b****6 文档编号:17897484 上传时间:2022-12-12 格式:DOCX 页数:25 大小:23.50KB
下载 相关 举报
Java并发编程实践Callable异步回调FutureFutureTask用法Word格式文档下载.docx_第1页
第1页 / 共25页
Java并发编程实践Callable异步回调FutureFutureTask用法Word格式文档下载.docx_第2页
第2页 / 共25页
Java并发编程实践Callable异步回调FutureFutureTask用法Word格式文档下载.docx_第3页
第3页 / 共25页
Java并发编程实践Callable异步回调FutureFutureTask用法Word格式文档下载.docx_第4页
第4页 / 共25页
Java并发编程实践Callable异步回调FutureFutureTask用法Word格式文档下载.docx_第5页
第5页 / 共25页
点击查看更多>>
下载资源
资源描述

Java并发编程实践Callable异步回调FutureFutureTask用法Word格式文档下载.docx

《Java并发编程实践Callable异步回调FutureFutureTask用法Word格式文档下载.docx》由会员分享,可在线阅读,更多相关《Java并发编程实践Callable异步回调FutureFutureTask用法Word格式文档下载.docx(25页珍藏版)》请在冰豆网上搜索。

Java并发编程实践Callable异步回调FutureFutureTask用法Word格式文档下载.docx

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

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 初中教育 > 数学

copyright@ 2008-2022 冰豆网网站版权所有

经营许可证编号:鄂ICP备2022015515号-1