|
马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有帐号?立即注册
x
学习JAVA的目的更多的是培养自身的工作能力,我觉得工作能力的一个核心就是:独立思考能力,因为只有独立思考后,才会有自己的见解
提要
后面一章,我们进修了“公允锁”猎取锁的具体流程;这里,我们再来看看“公允锁”开释锁的历程。内容包含:
参考代码
开释公允锁(基于JDK1.7.0_40)
“公允锁”的猎取历程请参考“Java多线程系列--“JUC锁”03之公允锁(一)”,锁的利用示例请参考“Java多线程系列--“JUC锁”02之互斥锁ReentrantLock”。
注重:
(01)这里是以“公允锁”来举行申明。
(02)关于本章的术语,如“AQS”,“CAS函数”,“CLH行列”,“公允锁”,“非公允锁”,“独有锁”,“共享锁”等外容,请参考Java多线程系列--“JUC锁”03之公允锁(一)的基础观点。
上面给出Java1.7.0_40版本中,ReentrantLock和AQS的源码,仅供参考!
ReentranLock.java- /*
- *ORACLEPROPRIETARY/CONFIDENTIAL.Useissubjecttolicenseterms.
- *
- *
- *
- *
- *
- *
- *
- *
- *
- *
- *
- *
- *
- *
- *
- *
- *
- *
- *
- *
- */
- /*
- *
- *
- *
- *
- *
- *WrittenbyDougLeawithassistancefrommembersofJCPJSR-166
- *ExpertGroupandreleasedtothepublicdomain,asexplainedat
- *http://creativecommons.org/publicdomain/zero/1.0/
- */
- packagejava.util.concurrent.locks;
- importjava.util.*;
- importjava.util.concurrent.*;
- importjava.util.concurrent.atomic.*;
- /**
- *Areentrantmutualexclusion{@linkLock}withthesamebasic
- *behaviorandsemanticsastheimplicitmonitorlockaccessedusing
- *{@codesynchronized}methodsandstatements,butwithextended
- *capabilities.
- *
- *<p>A{@codeReentrantLock}is<em>owned</em>bythethreadlast
- *successfullylocking,butnotyetunlockingit.Athreadinvoking
- *{@codelock}willreturn,successfullyacquiringthelock,when
- *thelockisnotownedbyanotherthread.Themethodwillreturn
- *immediatelyifthecurrentthreadalreadyownsthelock.Thiscan
- *becheckedusingmethods{@link#isHeldByCurrentThread},and{@link
- *#getHoldCount}.
- *
- *<p>Theconstructorforthisclassacceptsanoptional
- *<em>fairness</em>parameter.Whenset{@codetrue},under
- *contention,locksfavorgrantingaccesstothelongest-waiting
- *thread.Otherwisethislockdoesnotguaranteeanyparticular
- *accessorder.Programsusingfairlocksaccessedbymanythreads
- *maydisplayloweroverallthroughput(i.e.,areslower;oftenmuch
- *slower)thanthoseusingthedefaultsetting,buthavesmaller
- *variancesintimestoobtainlocksandguaranteelackof
- *starvation.Notehowever,thatfairnessoflocksdoesnotguarantee
- *fairnessofthreadscheduling.Thus,oneofmanythreadsusinga
- *fairlockmayobtainitmultipletimesinsuccessionwhileother
- *activethreadsarenotprogressingandnotcurrentlyholdingthe
- *lock.
- *Alsonotethattheuntimed{@link#tryLock()tryLock}methoddoesnot
- *honorthefairnesssetting.Itwillsucceedifthelock
- *isavailableevenifotherthreadsarewaiting.
- *
- *<p>Itisrecommendedpracticeto<em>always</em>immediately
- *followacallto{@codelock}witha{@codetry}block,most
- *typicallyinabefore/afterconstructionsuchas:
- *
- *<pre>
- *classX{
- *privatefinalReentrantLocklock=newReentrantLock();
- *//...
- *
- *publicvoidm(){
- *lock.lock();//blockuntilconditionholds
- *try{
- *//...methodbody
- *}finally{
- *lock.unlock()
- *}
- *}
- *}
- *</pre>
- *
- *<p>Inadditiontoimplementingthe{@linkLock}interface,this
- *classdefinesmethods{@codeisLocked}and
- *{@codegetLockQueueLength},aswellassomeassociated
- *{@codeprotected}accessmethodsthatmaybeusefulfor
- *instrumentationandmonitoring.
- *
- *<p>Serializationofthisclassbehavesinthesamewayasbuilt-in
- *locks:adeserializedlockisintheunlockedstate,regardlessof
- *itsstatewhenserialized.
- *
- *<p>Thislocksupportsamaximumof2147483647recursivelocksby
- *thesamethread.Attemptstoexceedthislimitresultin
- *{@linkError}throwsfromlockingmethods.
- *
- *@since1.5
- *@authorDougLea
- */
- publicclassReentrantLockimplementsLock,java.io.Serializable{
- privatestaticfinallongserialVersionUID=7373984872572414699L;
- /**Synchronizerprovidingallimplementationmechanics*/
- privatefinalSyncsync;
- /**
- *Baseofsynchronizationcontrolforthislock.Subclassed
- *intofairandnonfairversionsbelow.UsesAQSstateto
- *representthenumberofholdsonthelock.
- */
- abstractstaticclassSyncextendsAbstractQueuedSynchronizer{
- privatestaticfinallongserialVersionUID=-5179523762034025860L;
- /**
- *Performs{@linkLock#lock}.Themainreasonforsubclassing
- *istoallowfastpathfornonfairversion.
- */
- abstractvoidlock();
- /**
- *Performsnon-fairtryLock.tryAcquireis
- *implementedinsubclasses,butbothneednonfair
- *tryfortrylockmethod.
- */
- finalbooleannonfairTryAcquire(intacquires){
- finalThreadcurrent=Thread.currentThread();
- intc=getState();
- if(c==0){
- if(compareAndSetState(0,acquires)){
- setExclusiveOwnerThread(current);
- returntrue;
- }
- }
- elseif(current==getExclusiveOwnerThread()){
- intnextc=c+acquires;
- if(nextc<0)//overflow
- thrownewError("Maximumlockcountexceeded");
- setState(nextc);
- returntrue;
- }
- returnfalse;
- }
- protectedfinalbooleantryRelease(intreleases){
- intc=getState()-releases;
- if(Thread.currentThread()!=getExclusiveOwnerThread())
- thrownewIllegalMonitorStateException();
- booleanfree=false;
- if(c==0){
- free=true;
- setExclusiveOwnerThread(null);
- }
- setState(c);
- returnfree;
- }
- protectedfinalbooleanisHeldExclusively(){
- //Whilewemustingeneralreadstatebeforeowner,
- //wedontneedtodosotocheckifcurrentthreadisowner
- returngetExclusiveOwnerThread()==Thread.currentThread();
- }
- finalConditionObjectnewCondition(){
- returnnewConditionObject();
- }
- //Methodsrelayedfromouterclass
- finalThreadgetOwner(){
- returngetState()==0?null:getExclusiveOwnerThread();
- }
- finalintgetHoldCount(){
- returnisHeldExclusively()?getState():0;
- }
- finalbooleanisLocked(){
- returngetState()!=0;
- }
- /**
- *Reconstitutesthislockinstancefromastream.
- *@paramsthestream
- */
- privatevoidreadObject(java.io.ObjectInputStreams)
- throwsjava.io.IOException,ClassNotFoundException{
- s.defaultReadObject();
- setState(0);//resettounlockedstate
- }
- }
- /**
- *Syncobjectfornon-fairlocks
- */
- staticfinalclassNonfairSyncextendsSync{
- privatestaticfinallongserialVersionUID=7316153563782823691L;
- /**
- *Performslock.Tryimmediatebarge,backinguptonormal
- *acquireonfailure.
- */
- finalvoidlock(){
- if(compareAndSetState(0,1))
- setExclusiveOwnerThread(Thread.currentThread());
- else
- acquire(1);
- }
- protectedfinalbooleantryAcquire(intacquires){
- returnnonfairTryAcquire(acquires);
- }
- }
- /**
- *Syncobjectforfairlocks
- */
- staticfinalclassFairSyncextendsSync{
- privatestaticfinallongserialVersionUID=-3000897897090466540L;
- finalvoidlock(){
- acquire(1);
- }
- /**
- *FairversionoftryAcquire.Dontgrantaccessunless
- *recursivecallornowaitersorisfirst.
- */
- protectedfinalbooleantryAcquire(intacquires){
- finalThreadcurrent=Thread.currentThread();
- intc=getState();
- if(c==0){
- if(!hasQueuedPredecessors()&&
- compareAndSetState(0,acquires)){
- setExclusiveOwnerThread(current);
- returntrue;
- }
- }
- elseif(current==getExclusiveOwnerThread()){
- intnextc=c+acquires;
- if(nextc<0)
- thrownewError("Maximumlockcountexceeded");
- setState(nextc);
- returntrue;
- }
- returnfalse;
- }
- }
- /**
- *Createsaninstanceof{@codeReentrantLock}.
- *Thisisequivalenttousing{@codeReentrantLock(false)}.
- */
- publicReentrantLock(){
- sync=newNonfairSync();
- }
- /**
- *Createsaninstanceof{@codeReentrantLock}withthe
- *givenfairnesspolicy.
- *
- *@paramfair{@codetrue}ifthislockshoulduseafairorderingpolicy
- */
- publicReentrantLock(booleanfair){
- sync=fair?newFairSync():newNonfairSync();
- }
- /**
- *Acquiresthelock.
- *
- *<p>Acquiresthelockifitisnotheldbyanotherthreadandreturns
- *immediately,settingthelockholdcounttoone.
- *
- *<p>Ifthecurrentthreadalreadyholdsthelockthenthehold
- *countisincrementedbyoneandthemethodreturnsimmediately.
- *
- *<p>Ifthelockisheldbyanotherthreadthenthe
- *currentthreadbecomesdisabledforthreadscheduling
- *purposesandliesdormantuntilthelockhasbeenacquired,
- *atwhichtimethelockholdcountissettoone.
- */
- publicvoidlock(){
- sync.lock();
- }
- /**
- *Acquiresthelockunlessthecurrentthreadis
- *{@linkplainThread#interruptinterrupted}.
- *
- *<p>Acquiresthelockifitisnotheldbyanotherthreadandreturns
- *immediately,settingthelockholdcounttoone.
- *
- *<p>Ifthecurrentthreadalreadyholdsthislockthentheholdcount
- *isincrementedbyoneandthemethodreturnsimmediately.
- *
- *<p>Ifthelockisheldbyanotherthreadthenthe
- *currentthreadbecomesdisabledforthreadscheduling
- *purposesandliesdormantuntiloneoftwothingshappens:
- *
- *<ul>
- *
- *<li>Thelockisacquiredbythecurrentthread;or
- *
- *<li>Someotherthread{@linkplainThread#interruptinterrupts}the
- *currentthread.
- *
- *</ul>
- *
- *<p>Ifthelockisacquiredbythecurrentthreadthenthelockhold
- *countissettoone.
- *
- *<p>Ifthecurrentthread:
- *
- *<ul>
- *
- *<li>hasitsinterruptedstatussetonentrytothismethod;or
- *
- *<li>is{@linkplainThread#interruptinterrupted}whileacquiring
- *thelock,
- *
- *</ul>
- *
- *then{@linkInterruptedException}isthrownandthecurrentthreads
- *interruptedstatusiscleared.
- *
- *<p>Inthisimplementation,asthismethodisanexplicit
- *interruptionpoint,preferenceisgiventorespondingtothe
- *interruptovernormalorreentrantacquisitionofthelock.
- *
- *@throwsInterruptedExceptionifthecurrentthreadisinterrupted
- */
- publicvoidlockInterruptibly()throwsInterruptedException{
- sync.acquireInterruptibly(1);
- }
- /**
- *Acquiresthelockonlyifitisnotheldbyanotherthreadatthetime
- *ofinvocation.
- *
- *<p>Acquiresthelockifitisnotheldbyanotherthreadand
- *returnsimmediatelywiththevalue{@codetrue},settingthe
- *lockholdcounttoone.Evenwhenthislockhasbeensettousea
- *fairorderingpolicy,acallto{@codetryLock()}<em>will</em>
- *immediatelyacquirethelockifitisavailable,whetherornot
- *otherthreadsarecurrentlywaitingforthelock.
- *This"barging"behaviorcanbeusefulincertain
- *circumstances,eventhoughitbreaksfairness.Ifyouwanttohonor
- *thefairnesssettingforthislock,thenuse
- *{@link#tryLock(long,TimeUnit)tryLock(0,TimeUnit.SECONDS)}
- *whichisalmostequivalent(italsodetectsinterruption).
- *
- *<p>Ifthecurrentthreadalreadyholdsthislockthenthehold
- *countisincrementedbyoneandthemethodreturns{@codetrue}.
- *
- *<p>Ifthelockisheldbyanotherthreadthenthismethodwillreturn
- *immediatelywiththevalue{@codefalse}.
- *
- *@return{@codetrue}ifthelockwasfreeandwasacquiredbythe
- *currentthread,orthelockwasalreadyheldbythecurrent
- *thread;and{@codefalse}otherwise
- */
- publicbooleantryLock(){
- returnsync.nonfairTryAcquire(1);
- }
- /**
- *Acquiresthelockifitisnotheldbyanotherthreadwithinthegiven
- *waitingtimeandthecurrentthreadhasnotbeen
- *{@linkplainThread#interruptinterrupted}.
- *
- *<p>Acquiresthelockifitisnotheldbyanotherthreadandreturns
- *immediatelywiththevalue{@codetrue},settingthelockholdcount
- *toone.Ifthislockhasbeensettouseafairorderingpolicythen
- *anavailablelock<em>willnot</em>beacquiredifanyotherthreads
- *arewaitingforthelock.Thisisincontrasttothe{@link#tryLock()}
- *method.Ifyouwantatimed{@codetryLock}thatdoespermitbargingon
- *afairlockthencombinethetimedandun-timedformstogether:
- *
- *<pre>if(lock.tryLock()||lock.tryLock(timeout,unit)){...}
- *</pre>
- *
- *<p>Ifthecurrentthread
- *alreadyholdsthislockthentheholdcountisincrementedbyoneand
- *themethodreturns{@codetrue}.
- *
- *<p>Ifthelockisheldbyanotherthreadthenthe
- *currentthreadbecomesdisabledforthreadscheduling
- *purposesandliesdormantuntiloneofthreethingshappens:
- *
- *<ul>
- *
- *<li>Thelockisacquiredbythecurrentthread;or
- *
- *<li>Someotherthread{@linkplainThread#interruptinterrupts}
- *thecurrentthread;or
- *
- *<li>Thespecifiedwaitingtimeelapses
- *
- *</ul>
- *
- *<p>Ifthelockisacquiredthenthevalue{@codetrue}isreturnedand
- *thelockholdcountissettoone.
- *
- *<p>Ifthecurrentthread:
- *
- *<ul>
- *
- *<li>hasitsinterruptedstatussetonentrytothismethod;or
- *
- *<li>is{@linkplainThread#interruptinterrupted}while
- *acquiringthelock,
- *
- *</ul>
- *then{@linkInterruptedException}isthrownandthecurrentthreads
- *interruptedstatusiscleared.
- *
- *<p>Ifthespecifiedwaitingtimeelapsesthenthevalue{@codefalse}
- *isreturned.Ifthetimeislessthanorequaltozero,themethod
- *willnotwaitatall.
- *
- *<p>Inthisimplementation,asthismethodisanexplicit
- *interruptionpoint,preferenceisgiventorespondingtothe
- *interruptovernormalorreentrantacquisitionofthelock,and
- *overreportingtheelapseofthewaitingtime.
- *
- *@paramtimeoutthetimetowaitforthelock
- *@paramunitthetimeunitofthetimeoutargument
- *@return{@codetrue}ifthelockwasfreeandwasacquiredbythe
- *currentthread,orthelockwasalreadyheldbythecurrent
- *thread;and{@codefalse}ifthewaitingtimeelapsedbefore
- *thelockcouldbeacquired
- *@throwsInterruptedExceptionifthecurrentthreadisinterrupted
- *@throwsNullPointerExceptionifthetimeunitisnull
- *
- */
- publicbooleantryLock(longtimeout,TimeUnitunit)
- throwsInterruptedException{
- returnsync.tryAcquireNanos(1,unit.toNanos(timeout));
- }
- /**
- *Attemptstoreleasethislock.
- *
- *<p>Ifthecurrentthreadistheholderofthislockthenthehold
- *countisdecremented.Iftheholdcountisnowzerothenthelock
- *isreleased.Ifthecurrentthreadisnottheholderofthis
- *lockthen{@linkIllegalMonitorStateException}isthrown.
- *
- *@throwsIllegalMonitorStateExceptionifthecurrentthreaddoesnot
- *holdthislock
- */
- publicvoidunlock(){
- sync.release(1);
- }
- /**
- *Returnsa{@linkCondition}instanceforusewiththis
- *{@linkLock}instance.
- *
- *<p>Thereturned{@linkCondition}instancesupportsthesame
- *usagesasdothe{@linkObject}monitormethods({@link
- *Object#wait()wait},{@linkObject#notifynotify},and{@link
- *Object#notifyAllnotifyAll})whenusedwiththebuilt-in
- *monitorlock.
- *
- *<ul>
- *
- *<li>Ifthislockisnotheldwhenanyofthe{@linkCondition}
- *{@linkplainCondition#await()waiting}or{@linkplain
- *Condition#signalsignalling}methodsarecalled,thenan{@link
- *IllegalMonitorStateException}isthrown.
- *
- *<li>Whenthecondition{@linkplainCondition#await()waiting}
- *methodsarecalledthelockisreleasedand,beforethey
- *return,thelockisreacquiredandthelockholdcountrestored
- *towhatitwaswhenthemethodwascalled.
- *
- *<li>Ifathreadis{@linkplainThread#interruptinterrupted}
- *whilewaitingthenthewaitwillterminate,an{@link
- *InterruptedException}willbethrown,andthethreads
- *interruptedstatuswillbecleared.
- *
- *<li>WaitingthreadsaresignalledinFIFOorder.
- *
- *<li>Theorderingoflockreacquisitionforthreadsreturning
- *fromwaitingmethodsisthesameasforthreadsinitially
- *acquiringthelock,whichisinthedefaultcasenotspecified,
- *butfor<em>fair</em>locksfavorsthosethreadsthathavebeen
- *waitingthelongest.
- *
- *</ul>
- *
- *@returntheConditionobject
- */
- publicConditionnewCondition(){
- returnsync.newCondition();
- }
- /**
- *Queriesthenumberofholdsonthislockbythecurrentthread.
- *
- *<p>Athreadhasaholdonalockforeachlockactionthatisnot
- *matchedbyanunlockaction.
- *
- *<p>Theholdcountinformationistypicallyonlyusedfortestingand
- *debuggingpurposes.Forexample,ifacertainsectionofcodeshould
- *notbeenteredwiththelockalreadyheldthenwecanassertthat
- *fact:
- *
- *<pre>
- *classX{
- *ReentrantLocklock=newReentrantLock();
- *//...
- *publicvoidm(){
- *assertlock.getHoldCount()==0;
- *lock.lock();
- *try{
- *//...methodbody
- *}finally{
- *lock.unlock();
- *}
- *}
- *}
- *</pre>
- *
- *@returnthenumberofholdsonthislockbythecurrentthread,
- *orzeroifthislockisnotheldbythecurrentthread
- */
- publicintgetHoldCount(){
- returnsync.getHoldCount();
- }
- /**
- *Queriesifthislockisheldbythecurrentthread.
- *
- *<p>Analogoustothe{@linkThread#holdsLock}methodforbuilt-in
- *monitorlocks,thismethodistypicallyusedfordebuggingand
- *testing.Forexample,amethodthatshouldonlybecalledwhile
- *alockisheldcanassertthatthisisthecase:
- *
- *<pre>
- *classX{
- *ReentrantLocklock=newReentrantLock();
- *//...
- *
- *publicvoidm(){
- *assertlock.isHeldByCurrentThread();
- *//...methodbody
- *}
- *}
- *</pre>
- *
- *<p>Itcanalsobeusedtoensurethatareentrantlockisused
- *inanon-reentrantmanner,forexample:
- *
- *<pre>
- *classX{
- *ReentrantLocklock=newReentrantLock();
- *//...
- *
- *publicvoidm(){
- *assert!lock.isHeldByCurrentThread();
- *lock.lock();
- *try{
- *//...methodbody
- *}finally{
- *lock.unlock();
- *}
- *}
- *}
- *</pre>
- *
- *@return{@codetrue}ifcurrentthreadholdsthislockand
- *{@codefalse}otherwise
- */
- publicbooleanisHeldByCurrentThread(){
- returnsync.isHeldExclusively();
- }
- /**
- *Queriesifthislockisheldbyanythread.Thismethodis
- *designedforuseinmonitoringofthesystemstate,
- *notforsynchronizationcontrol.
- *
- *@return{@codetrue}ifanythreadholdsthislockand
- *{@codefalse}otherwise
- */
- publicbooleanisLocked(){
- returnsync.isLocked();
- }
- /**
- *Returns{@codetrue}ifthislockhasfairnesssettrue.
- *
- *@return{@codetrue}ifthislockhasfairnesssettrue
- */
- publicfinalbooleanisFair(){
- returnsyncinstanceofFairSync;
- }
- /**
- *Returnsthethreadthatcurrentlyownsthislock,or
- *{@codenull}ifnotowned.Whenthismethodiscalledbya
- *threadthatisnottheowner,thereturnvaluereflectsa
- *best-effortapproximationofcurrentlockstatus.Forexample,
- *theownermaybemomentarily{@codenull}evenifthereare
- *threadstryingtoacquirethelockbuthavenotyetdoneso.
- *Thismethodisdesignedtofacilitateconstructionof
- *subclassesthatprovidemoreextensivelockmonitoring
- *facilities.
- *
- *@returntheowner,or{@codenull}ifnotowned
- */
- protectedThreadgetOwner(){
- returnsync.getOwner();
- }
- /**
- *Querieswhetheranythreadsarewaitingtoacquirethislock.Notethat
- *becausecancellationsmayoccuratanytime,a{@codetrue}
- *returndoesnotguaranteethatanyotherthreadwillever
- *acquirethislock.Thismethodisdesignedprimarilyforusein
- *monitoringofthesystemstate.
- *
- *@return{@codetrue}iftheremaybeotherthreadswaitingto
- *acquirethelock
- */
- publicfinalbooleanhasQueuedThreads(){
- returnsync.hasQueuedThreads();
- }
- /**
- *Querieswhetherthegiventhreadiswaitingtoacquirethis
- *lock.Notethatbecausecancellationsmayoccuratanytime,a
- *{@codetrue}returndoesnotguaranteethatthisthread
- *willeveracquirethislock.Thismethodisdesignedprimarilyforuse
- *inmonitoringofthesystemstate.
- *
- *@paramthreadthethread
- *@return{@codetrue}ifthegiventhreadisqueuedwaitingforthislock
- *@throwsNullPointerExceptionifthethreadisnull
- */
- publicfinalbooleanhasQueuedThread(Threadthread){
- returnsync.isQueued(thread);
- }
- /**
- *Returnsanestimateofthenumberofthreadswaitingto
- *acquirethislock.Thevalueisonlyanestimatebecausethenumberof
- *threadsmaychangedynamicallywhilethismethodtraverses
- *internaldatastructures.Thismethodisdesignedforusein
- *monitoringofthesystemstate,notforsynchronization
- *control.
- *
- *@returntheestimatednumberofthreadswaitingforthislock
- */
- publicfinalintgetQueueLength(){
- returnsync.getQueueLength();
- }
- /**
- *Returnsacollectioncontainingthreadsthatmaybewaitingto
- *acquirethislock.Becausetheactualsetofthreadsmaychange
- *dynamicallywhileconstructingthisresult,thereturned
- *collectionisonlyabest-effortestimate.Theelementsofthe
- *returnedcollectionareinnoparticularorder.Thismethodis
- *designedtofacilitateconstructionofsubclassesthatprovide
- *moreextensivemonitoringfacilities.
- *
- *@returnthecollectionofthreads
- */
- protectedCollection<Thread>getQueuedThreads(){
- returnsync.getQueuedThreads();
- }
- /**
- *Querieswhetheranythreadsarewaitingonthegivencondition
- *associatedwiththislock.Notethatbecausetimeoutsand
- *interruptsmayoccuratanytime,a{@codetrue}returndoes
- *notguaranteethatafuture{@codesignal}willawakenany
- *threads.Thismethodisdesignedprimarilyforusein
- *monitoringofthesystemstate.
- *
- *@paramconditionthecondition
- *@return{@codetrue}ifthereareanywaitingthreads
- *@throwsIllegalMonitorStateExceptionifthislockisnotheld
- *@throwsIllegalArgumentExceptionifthegivenconditionis
- *notassociatedwiththislock
- *@throwsNullPointerExceptioniftheconditionisnull
- */
- publicbooleanhasWaiters(Conditioncondition){
- if(condition==null)
- thrownewNullPointerException();
- if(!(conditioninstanceofAbstractQueuedSynchronizer.ConditionObject))
- thrownewIllegalArgumentException("notowner");
- returnsync.hasWaiters((AbstractQueuedSynchronizer.ConditionObject)condition);
- }
- /**
- *Returnsanestimateofthenumberofthreadswaitingonthe
- *givenconditionassociatedwiththislock.Notethatbecause
- *timeoutsandinterruptsmayoccuratanytime,theestimate
- *servesonlyasanupperboundontheactualnumberofwaiters.
- *Thismethodisdesignedforuseinmonitoringofthesystem
- *state,notforsynchronizationcontrol.
- *
- *@paramconditionthecondition
- *@returntheestimatednumberofwaitingthreads
- *@throwsIllegalMonitorStateExceptionifthislockisnotheld
- *@throwsIllegalArgumentExceptionifthegivenconditionis
- *notassociatedwiththislock
- *@throwsNullPointerExceptioniftheconditionisnull
- */
- publicintgetWaitQueueLength(Conditioncondition){
- if(condition==null)
- thrownewNullPointerException();
- if(!(conditioninstanceofAbstractQueuedSynchronizer.ConditionObject))
- thrownewIllegalArgumentException("notowner");
- returnsync.getWaitQueueLength((AbstractQueuedSynchronizer.ConditionObject)
- condition);
- }
- /**
- *Returnsacollectioncontainingthosethreadsthatmaybe
- *waitingonthegivenconditionassociatedwiththislock.
- *Becausetheactualsetofthreadsmaychangedynamicallywhile
- *constructingthisresult,thereturnedcollectionisonlya
- *best-effortestimate.Theelementsofthereturnedcollection
- *areinnoparticularorder.Thismethodisdesignedto
- *facilitateconstructionofsubclassesthatprovidemore
- *extensiveconditionmonitoringfacilities.
- *
- *@paramconditionthecondition
- *@returnthecollectionofthreads
- *@throwsIllegalMonitorStateExceptionifthislockisnotheld
- *@throwsIllegalArgumentExceptionifthegivenconditionis
- *notassociatedwiththislock
- *@throwsNullPointerExceptioniftheconditionisnull
- */
- protectedCollection<Thread>getWaitingThreads(Conditioncondition){
- if(condition==null)
- thrownewNullPointerException();
- if(!(conditioninstanceofAbstractQueuedSynchronizer.ConditionObject))
- thrownewIllegalArgumentException("notowner");
- returnsync.getWaitingThreads((AbstractQueuedSynchronizer.ConditionObject)
- condition);
- }
- /**
- *Returnsastringidentifyingthislock,aswellasitslockstate.
- *Thestate,inbrackets,includeseithertheString{@code"Unlocked"}
- *ortheString{@code"Lockedby"}followedbythe
- *{@linkplainThread#getNamename}oftheowningthread.
- *
- *@returnastringidentifyingthislock,aswellasitslockstate
- */
- publicStringtoString(){
- Threado=sync.getOwner();
- returnsuper.toString()+((o==null)?
- "[Unlocked]":
- "[Lockedbythread"+o.getName()+"]
- ");
- }
- }
复制代码 <p>
有了这样一个呼声:让java代替C语言成为基本语言。这些足以说明java简单易学的这个优点。其次,java的功能强大,前面我也提到了,EJB3.0的推出使java成为了大型项目的首选。 |
|