灵魂腐蚀 发表于 2015-1-18 11:00:49

了解下JAVA的Java多线程:“JUC锁”04之公允锁(二)

学习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)?
"":
"

");
}
}<p>
有了这样一个呼声:让java代替C语言成为基本语言。这些足以说明java简单易学的这个优点。其次,java的功能强大,前面我也提到了,EJB3.0的推出使java成为了大型项目的首选。

admin 发表于 2015-1-20 12:44:34

那么我书也看了,程序也做了,别人问我的问题我都能解决了,是不是就成为高手了呢?当然没那么简单,这只是万里长征走完了第一步。不信?那你出去接一个项目,你知道怎么下手吗,你知道怎么设计吗,你知道怎么组织人员进行开发吗?你现在脑子里除了一些散乱的代码之外,可能再没有别的东西了吧!

不帅 发表于 2015-1-20 21:10:54

不过,每次的执行编译后的字节码需要消耗一定的时间,这同时也在一定程度上降低了 Java 程序的运行效率。

小女巫 发表于 2015-1-21 16:35:16

其实说这种话的人就如当年小日本号称“三个月拿下中国”一样大言不惭。不是Tomjava泼你冷水,你现在只是学到了Java的骨架,却还没有学到Java的精髓。接下来你得研究设计模式了。

灵魂腐蚀 发表于 2015-1-26 21:00:08

至于JDBC,就不用我多说了,你如果用java编过存取数据库的程序,就应该很熟悉。还有,如果你要用Java编发送电子邮件的程序,你就得看看Javamail 了。

莫相离 发表于 2015-2-4 20:22:05

至于JDBC,就不用我多说了,你如果用java编过存取数据库的程序,就应该很熟悉。还有,如果你要用Java编发送电子邮件的程序,你就得看看Javamail 了。

飘灵儿 发表于 2015-2-10 06:26:50

你就该学一学Servlet了。Servlet就是服务器端小程序,他负责生成发送给客户端的HTML文件。JSP在执行时,也是先转换成Servlet再运行的。虽说JSP理论上可以完全取代Servlet,这也是SUN推出JSP的本意,可是Servlet用来控制流程跳转还是挺方便的,也令程序更清晰。接下来你应该学习一下Javabean了,可能你早就看不管JSP在HTML中嵌Java代码的混乱方式了,这种方式跟ASP又有什么区别呢?

透明 发表于 2015-2-28 23:02:53

学Java必读的两个开源程序就是Jive和Pet Store.。 Jive是国外一个非常著名的BBS程序,完全开放源码。论坛的设计采用了很多先进的技术,如Cache、用户认证、Filter、XML等,而且论坛完全屏蔽了对数据库的访问,可以很轻易的在不同数据库中移植。论坛还有方便的安装和管理程序,这是我们平时编程时容易忽略的一部份(中国程序员一般只注重编程的技术含量,却完全不考虑用户的感受,这就是我们与国外软件的差距所在)。

飘飘悠悠 发表于 2015-3-10 09:59:11

任职于太阳微系统的詹姆斯·高斯林等人于1990年代初开发Java语言的雏形,最初被命名为Oak,目标设置在家用电器等小型系统的程序语言

小妖女 发表于 2015-3-17 06:10:34

Java是一个纯的面向对象的程序设计语言,它继承了 C++语言面向对象技术的核心。Java舍弃了C ++语言中容易引起错误的指针(以引用取代)、运算符重载(operator overloading)

活着的死人 发表于 2015-3-23 22:58:49

是一种使网页(Web Page)由静态(Static)转变为动态(Dynamic)的语言
页: [1]
查看完整版本: 了解下JAVA的Java多线程:“JUC锁”04之公允锁(二)