java多线程之异步future机制的原理和实现.doc
JAVA多线程之异步FUTURE机制的原理和实现这篇文章主要为大家详细介绍了JAVA多线程之异步FUTURE机制的原理和实现,感兴趣的小伙伴们可以参考一下项目中经常有些任务需要异步提交到线程池中去执行,而主线程往往需要知道异步执行产生的结果,这时我们要怎么做呢用RUNNABLE是无法实现的,我们需要用CALLABLE看下面的代码IMPORTJAVAUTILCONCURRENTCALLABLEIMPORTJAVAUTILCONCURRENTCUTIONEXCEPTIONIMPORTJAVAUTILCONCURRENTCUTORSERVICEIMPORTJAVAUTILCONCURRENTCUTORSIMPORTJAVAUTILCONCURRENTFUTUREPUBLICCLASSADDTASKIMPLEMENTSCALLABLE{PRIVATEINTA,BPUBLICADDTASKINTA,INTB{THISAATHISBB}OVERRIDEPUBLICINTEGERCALLTHROWSEXCEPTION{INTEGERRESULTABRETURNRESULT}PUBLICSTATICVOIDMAINSTRINGARGSTHROWSINTERRUPTEDEXCEPTION,CUTIONEXCEPTION{CUTORSERVICECUTORCUTORSNEWSINGLETHREADCUTOR//JDK目前为止返回的都是FUTURETASK的实例FUTUREFUTURECUTORNEWADDTASK1,2INTEGERRESULTFUTUREGET//只有当FUTURE的状态是已完成时FUTUREISDONETRUE,GET方法才会返回}}虽然可以实现获取异步执行结果的需求,但是我们发现这个FUTURE其实很不好用,因为它没有提供通知的机制,也就是说我们不知道FUTURE什么时候完成(如果我们需要轮询ISDONE来判断的话感觉就没有用这个的必要了)。看下JAVAUTILCONCURRENTFUTUREFUTURE的接口方法PUBLICINTERFACEFUTURE{BOOLEANCANCELBOOLEANMAYINTERRUPTIFRUNNINGBOOLEANISCANCELLEDBOOLEANISDONEVGETTHROWSINTERRUPTEDEXCEPTION,CUTIONEXCEPTIONVGETLONGTIMEOUT,TIMEUNITUNITTHROWSINTERRUPTEDEXCEPTION,CUTIONEXCEPTION,TIMEOUTEXCEPTION}由此可见JDK的FUTURE机制其实并不好用,如果能给这个FUTURE加个监听器,让它在完成时通知监听器的话就比较好用了,就像下面这个IFUTUREPACKAGEFUTUREIMPORTJAVAUTILCONCURRENTCANCELLATIONEXCEPTIONIMPORTJAVAUTILCONCURRENTFUTUREIMPORTJAVAUTILCONCURRENTTIMEUNIT/THERESULTOFANASYNCHRONOUSOPERATIONAUTHORLIXIAOHUIPARAM执行结果的类型参数/PUBLICINTERFACEIFUTUREEXTENDSFUTURE{BOOLEANISSUCCESS//是否成功VGETNOW//立即返回结果不管FUTURE是否处于完成状态THROWABLECAUSE//若执行失败时的原因BOOLEANISCANCELLABLE//是否可以取消IFUTUREAWAITTHROWSINTERRUPTEDEXCEPTION//等待FUTURE的完成BOOLEANAWAITLONGTIMEOUTMILLISTHROWSINTERRUPTEDEXCEPTION//超时等待FUTURE的完成BOOLEANAWAITLONGTIMEOUT,TIMEUNITTIMEUNITTHROWSINTERRUPTEDEXCEPTIONIFUTUREAWAITUNINTERRUPTIBLY//等待FUTURE的完成,不响应中断BOOLEANAWAITUNINTERRUPTIBLYLONGTIMEOUTMILLIS//超时等待FUTURE的完成,不响应中断BOOLEANAWAITUNINTERRUPTIBLYLONGTIMEOUT,TIMEUNITTIMEUNITIFUTUREADDLISTENERIFUTURELISTENERL//当FUTURE完成时,会通知这些加进来的监听器IFUTUREREMOVELISTENERIFUTURELISTENERL}接下来就一起来实现这个IFUTURE,在这之前要说明下OBJECTWAIT,OBJECTNOTIFYALL方法,因为整个FUTURE实现的原���的核心就是这两个方法看看JDK里面的解释PUBLICCLASSOBJECT{/CAUSESTHECURRENTTHREADTOWAITUNTILANOTHERTHREADINVOKESTHE{LINKJAVALANGOBJECTNOTIFY}ORTHE{LINKJAVALANGOBJECTNOTIFYALL}FORTHISOBJECTINOTHERWORDS,THISBEHAVESEXACTLYASIFITSIMPLYPERSTHECALL{CODEWAIT0}调用该方法后,当前线程会释放对象监视器锁,并让出CPU使用权。直到别的线程调用NOTIFY/NOTIFYALL/PUBLICFINALVOIDWAITTHROWSINTERRUPTEDEXCEPTION{WAIT0}/WAKESUPALLTHREADSTHATAREWAITINGONTHISOBJECT SMONITORATHREADWAITSONANOBJECT SMONITORBYCALLINGONEOFTHE{CODEWAIT}STHEAWAKENEDTHREADSWILLNOTBEABLETOPROCEEDUNTILTHECURRENTTHREADRELINQUISHESTHELOCKONTHISOBJECTTHEAWAKENEDTHREADSWILLCOMPETEINTHEUSUALMANNERWITHANYOTHERTHREADSTHATMIGHTBEACTIVELYCOMPETINGTOSYNCHRONIZEONTHISOBJECTFOREXAMPLE,THEAWAKENEDTHREADSENJOYNORELIABLEPRIVILEGEORDISADVANTAGEINBEINGTHENEXTTHREADTOLOCKTHISOBJECT/PUBLICFINALNATIVEVOIDNOTIFYALL}知道这个后,我们要自己实现FUTURE也就有了思路,当线程调用了IFUTUREAWAIT等一系列的方法时,如果FUTURE还未完成,那么就调用FUTUREWAIT方法使线程进入WAITING状态。而当别的线程设置FUTUR