仓酷云

标题: 了解下JAVA的Java多线程:“JUC锁”04之公允锁(二) [打印本页]

作者: 灵魂腐蚀    时间: 2015-1-18 11:00
标题: 了解下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
  1. /*
  2. *ORACLEPROPRIETARY/CONFIDENTIAL.Useissubjecttolicenseterms.
  3. *
  4. *
  5. *
  6. *
  7. *
  8. *
  9. *
  10. *
  11. *
  12. *
  13. *
  14. *
  15. *
  16. *
  17. *
  18. *
  19. *
  20. *
  21. *
  22. *
  23. */
  24. /*
  25. *
  26. *
  27. *
  28. *
  29. *
  30. *WrittenbyDougLeawithassistancefrommembersofJCPJSR-166
  31. *ExpertGroupandreleasedtothepublicdomain,asexplainedat
  32. *http://creativecommons.org/publicdomain/zero/1.0/
  33. */
  34. packagejava.util.concurrent.locks;
  35. importjava.util.*;
  36. importjava.util.concurrent.*;
  37. importjava.util.concurrent.atomic.*;
  38. /**
  39. *Areentrantmutualexclusion{@linkLock}withthesamebasic
  40. *behaviorandsemanticsastheimplicitmonitorlockaccessedusing
  41. *{@codesynchronized}methodsandstatements,butwithextended
  42. *capabilities.
  43. *
  44. *<p>A{@codeReentrantLock}is<em>owned</em>bythethreadlast
  45. *successfullylocking,butnotyetunlockingit.Athreadinvoking
  46. *{@codelock}willreturn,successfullyacquiringthelock,when
  47. *thelockisnotownedbyanotherthread.Themethodwillreturn
  48. *immediatelyifthecurrentthreadalreadyownsthelock.Thiscan
  49. *becheckedusingmethods{@link#isHeldByCurrentThread},and{@link
  50. *#getHoldCount}.
  51. *
  52. *<p>Theconstructorforthisclassacceptsanoptional
  53. *<em>fairness</em>parameter.Whenset{@codetrue},under
  54. *contention,locksfavorgrantingaccesstothelongest-waiting
  55. *thread.Otherwisethislockdoesnotguaranteeanyparticular
  56. *accessorder.Programsusingfairlocksaccessedbymanythreads
  57. *maydisplayloweroverallthroughput(i.e.,areslower;oftenmuch
  58. *slower)thanthoseusingthedefaultsetting,buthavesmaller
  59. *variancesintimestoobtainlocksandguaranteelackof
  60. *starvation.Notehowever,thatfairnessoflocksdoesnotguarantee
  61. *fairnessofthreadscheduling.Thus,oneofmanythreadsusinga
  62. *fairlockmayobtainitmultipletimesinsuccessionwhileother
  63. *activethreadsarenotprogressingandnotcurrentlyholdingthe
  64. *lock.
  65. *Alsonotethattheuntimed{@link#tryLock()tryLock}methoddoesnot
  66. *honorthefairnesssetting.Itwillsucceedifthelock
  67. *isavailableevenifotherthreadsarewaiting.
  68. *
  69. *<p>Itisrecommendedpracticeto<em>always</em>immediately
  70. *followacallto{@codelock}witha{@codetry}block,most
  71. *typicallyinabefore/afterconstructionsuchas:
  72. *
  73. *<pre>
  74. *classX{
  75. *privatefinalReentrantLocklock=newReentrantLock();
  76. *//...
  77. *
  78. *publicvoidm(){
  79. *lock.lock();//blockuntilconditionholds
  80. *try{
  81. *//...methodbody
  82. *}finally{
  83. *lock.unlock()
  84. *}
  85. *}
  86. *}
  87. *</pre>
  88. *
  89. *<p>Inadditiontoimplementingthe{@linkLock}interface,this
  90. *classdefinesmethods{@codeisLocked}and
  91. *{@codegetLockQueueLength},aswellassomeassociated
  92. *{@codeprotected}accessmethodsthatmaybeusefulfor
  93. *instrumentationandmonitoring.
  94. *
  95. *<p>Serializationofthisclassbehavesinthesamewayasbuilt-in
  96. *locks:adeserializedlockisintheunlockedstate,regardlessof
  97. *itsstatewhenserialized.
  98. *
  99. *<p>Thislocksupportsamaximumof2147483647recursivelocksby
  100. *thesamethread.Attemptstoexceedthislimitresultin
  101. *{@linkError}throwsfromlockingmethods.
  102. *
  103. *@since1.5
  104. *@authorDougLea
  105. */
  106. publicclassReentrantLockimplementsLock,java.io.Serializable{
  107. privatestaticfinallongserialVersionUID=7373984872572414699L;
  108. /**Synchronizerprovidingallimplementationmechanics*/
  109. privatefinalSyncsync;
  110. /**
  111. *Baseofsynchronizationcontrolforthislock.Subclassed
  112. *intofairandnonfairversionsbelow.UsesAQSstateto
  113. *representthenumberofholdsonthelock.
  114. */
  115. abstractstaticclassSyncextendsAbstractQueuedSynchronizer{
  116. privatestaticfinallongserialVersionUID=-5179523762034025860L;
  117. /**
  118. *Performs{@linkLock#lock}.Themainreasonforsubclassing
  119. *istoallowfastpathfornonfairversion.
  120. */
  121. abstractvoidlock();
  122. /**
  123. *Performsnon-fairtryLock.tryAcquireis
  124. *implementedinsubclasses,butbothneednonfair
  125. *tryfortrylockmethod.
  126. */
  127. finalbooleannonfairTryAcquire(intacquires){
  128. finalThreadcurrent=Thread.currentThread();
  129. intc=getState();
  130. if(c==0){
  131. if(compareAndSetState(0,acquires)){
  132. setExclusiveOwnerThread(current);
  133. returntrue;
  134. }
  135. }
  136. elseif(current==getExclusiveOwnerThread()){
  137. intnextc=c+acquires;
  138. if(nextc<0)//overflow
  139. thrownewError("Maximumlockcountexceeded");
  140. setState(nextc);
  141. returntrue;
  142. }
  143. returnfalse;
  144. }
  145. protectedfinalbooleantryRelease(intreleases){
  146. intc=getState()-releases;
  147. if(Thread.currentThread()!=getExclusiveOwnerThread())
  148. thrownewIllegalMonitorStateException();
  149. booleanfree=false;
  150. if(c==0){
  151. free=true;
  152. setExclusiveOwnerThread(null);
  153. }
  154. setState(c);
  155. returnfree;
  156. }
  157. protectedfinalbooleanisHeldExclusively(){
  158. //Whilewemustingeneralreadstatebeforeowner,
  159. //wedontneedtodosotocheckifcurrentthreadisowner
  160. returngetExclusiveOwnerThread()==Thread.currentThread();
  161. }
  162. finalConditionObjectnewCondition(){
  163. returnnewConditionObject();
  164. }
  165. //Methodsrelayedfromouterclass
  166. finalThreadgetOwner(){
  167. returngetState()==0?null:getExclusiveOwnerThread();
  168. }
  169. finalintgetHoldCount(){
  170. returnisHeldExclusively()?getState():0;
  171. }
  172. finalbooleanisLocked(){
  173. returngetState()!=0;
  174. }
  175. /**
  176. *Reconstitutesthislockinstancefromastream.
  177. *@paramsthestream
  178. */
  179. privatevoidreadObject(java.io.ObjectInputStreams)
  180. throwsjava.io.IOException,ClassNotFoundException{
  181. s.defaultReadObject();
  182. setState(0);//resettounlockedstate
  183. }
  184. }
  185. /**
  186. *Syncobjectfornon-fairlocks
  187. */
  188. staticfinalclassNonfairSyncextendsSync{
  189. privatestaticfinallongserialVersionUID=7316153563782823691L;
  190. /**
  191. *Performslock.Tryimmediatebarge,backinguptonormal
  192. *acquireonfailure.
  193. */
  194. finalvoidlock(){
  195. if(compareAndSetState(0,1))
  196. setExclusiveOwnerThread(Thread.currentThread());
  197. else
  198. acquire(1);
  199. }
  200. protectedfinalbooleantryAcquire(intacquires){
  201. returnnonfairTryAcquire(acquires);
  202. }
  203. }
  204. /**
  205. *Syncobjectforfairlocks
  206. */
  207. staticfinalclassFairSyncextendsSync{
  208. privatestaticfinallongserialVersionUID=-3000897897090466540L;
  209. finalvoidlock(){
  210. acquire(1);
  211. }
  212. /**
  213. *FairversionoftryAcquire.Dontgrantaccessunless
  214. *recursivecallornowaitersorisfirst.
  215. */
  216. protectedfinalbooleantryAcquire(intacquires){
  217. finalThreadcurrent=Thread.currentThread();
  218. intc=getState();
  219. if(c==0){
  220. if(!hasQueuedPredecessors()&&
  221. compareAndSetState(0,acquires)){
  222. setExclusiveOwnerThread(current);
  223. returntrue;
  224. }
  225. }
  226. elseif(current==getExclusiveOwnerThread()){
  227. intnextc=c+acquires;
  228. if(nextc<0)
  229. thrownewError("Maximumlockcountexceeded");
  230. setState(nextc);
  231. returntrue;
  232. }
  233. returnfalse;
  234. }
  235. }
  236. /**
  237. *Createsaninstanceof{@codeReentrantLock}.
  238. *Thisisequivalenttousing{@codeReentrantLock(false)}.
  239. */
  240. publicReentrantLock(){
  241. sync=newNonfairSync();
  242. }
  243. /**
  244. *Createsaninstanceof{@codeReentrantLock}withthe
  245. *givenfairnesspolicy.
  246. *
  247. *@paramfair{@codetrue}ifthislockshoulduseafairorderingpolicy
  248. */
  249. publicReentrantLock(booleanfair){
  250. sync=fair?newFairSync():newNonfairSync();
  251. }
  252. /**
  253. *Acquiresthelock.
  254. *
  255. *<p>Acquiresthelockifitisnotheldbyanotherthreadandreturns
  256. *immediately,settingthelockholdcounttoone.
  257. *
  258. *<p>Ifthecurrentthreadalreadyholdsthelockthenthehold
  259. *countisincrementedbyoneandthemethodreturnsimmediately.
  260. *
  261. *<p>Ifthelockisheldbyanotherthreadthenthe
  262. *currentthreadbecomesdisabledforthreadscheduling
  263. *purposesandliesdormantuntilthelockhasbeenacquired,
  264. *atwhichtimethelockholdcountissettoone.
  265. */
  266. publicvoidlock(){
  267. sync.lock();
  268. }
  269. /**
  270. *Acquiresthelockunlessthecurrentthreadis
  271. *{@linkplainThread#interruptinterrupted}.
  272. *
  273. *<p>Acquiresthelockifitisnotheldbyanotherthreadandreturns
  274. *immediately,settingthelockholdcounttoone.
  275. *
  276. *<p>Ifthecurrentthreadalreadyholdsthislockthentheholdcount
  277. *isincrementedbyoneandthemethodreturnsimmediately.
  278. *
  279. *<p>Ifthelockisheldbyanotherthreadthenthe
  280. *currentthreadbecomesdisabledforthreadscheduling
  281. *purposesandliesdormantuntiloneoftwothingshappens:
  282. *
  283. *<ul>
  284. *
  285. *<li>Thelockisacquiredbythecurrentthread;or
  286. *
  287. *<li>Someotherthread{@linkplainThread#interruptinterrupts}the
  288. *currentthread.
  289. *
  290. *</ul>
  291. *
  292. *<p>Ifthelockisacquiredbythecurrentthreadthenthelockhold
  293. *countissettoone.
  294. *
  295. *<p>Ifthecurrentthread:
  296. *
  297. *<ul>
  298. *
  299. *<li>hasitsinterruptedstatussetonentrytothismethod;or
  300. *
  301. *<li>is{@linkplainThread#interruptinterrupted}whileacquiring
  302. *thelock,
  303. *
  304. *</ul>
  305. *
  306. *then{@linkInterruptedException}isthrownandthecurrentthreads
  307. *interruptedstatusiscleared.
  308. *
  309. *<p>Inthisimplementation,asthismethodisanexplicit
  310. *interruptionpoint,preferenceisgiventorespondingtothe
  311. *interruptovernormalorreentrantacquisitionofthelock.
  312. *
  313. *@throwsInterruptedExceptionifthecurrentthreadisinterrupted
  314. */
  315. publicvoidlockInterruptibly()throwsInterruptedException{
  316. sync.acquireInterruptibly(1);
  317. }
  318. /**
  319. *Acquiresthelockonlyifitisnotheldbyanotherthreadatthetime
  320. *ofinvocation.
  321. *
  322. *<p>Acquiresthelockifitisnotheldbyanotherthreadand
  323. *returnsimmediatelywiththevalue{@codetrue},settingthe
  324. *lockholdcounttoone.Evenwhenthislockhasbeensettousea
  325. *fairorderingpolicy,acallto{@codetryLock()}<em>will</em>
  326. *immediatelyacquirethelockifitisavailable,whetherornot
  327. *otherthreadsarecurrentlywaitingforthelock.
  328. *This"barging"behaviorcanbeusefulincertain
  329. *circumstances,eventhoughitbreaksfairness.Ifyouwanttohonor
  330. *thefairnesssettingforthislock,thenuse
  331. *{@link#tryLock(long,TimeUnit)tryLock(0,TimeUnit.SECONDS)}
  332. *whichisalmostequivalent(italsodetectsinterruption).
  333. *
  334. *<p>Ifthecurrentthreadalreadyholdsthislockthenthehold
  335. *countisincrementedbyoneandthemethodreturns{@codetrue}.
  336. *
  337. *<p>Ifthelockisheldbyanotherthreadthenthismethodwillreturn
  338. *immediatelywiththevalue{@codefalse}.
  339. *
  340. *@return{@codetrue}ifthelockwasfreeandwasacquiredbythe
  341. *currentthread,orthelockwasalreadyheldbythecurrent
  342. *thread;and{@codefalse}otherwise
  343. */
  344. publicbooleantryLock(){
  345. returnsync.nonfairTryAcquire(1);
  346. }
  347. /**
  348. *Acquiresthelockifitisnotheldbyanotherthreadwithinthegiven
  349. *waitingtimeandthecurrentthreadhasnotbeen
  350. *{@linkplainThread#interruptinterrupted}.
  351. *
  352. *<p>Acquiresthelockifitisnotheldbyanotherthreadandreturns
  353. *immediatelywiththevalue{@codetrue},settingthelockholdcount
  354. *toone.Ifthislockhasbeensettouseafairorderingpolicythen
  355. *anavailablelock<em>willnot</em>beacquiredifanyotherthreads
  356. *arewaitingforthelock.Thisisincontrasttothe{@link#tryLock()}
  357. *method.Ifyouwantatimed{@codetryLock}thatdoespermitbargingon
  358. *afairlockthencombinethetimedandun-timedformstogether:
  359. *
  360. *<pre>if(lock.tryLock()||lock.tryLock(timeout,unit)){...}
  361. *</pre>
  362. *
  363. *<p>Ifthecurrentthread
  364. *alreadyholdsthislockthentheholdcountisincrementedbyoneand
  365. *themethodreturns{@codetrue}.
  366. *
  367. *<p>Ifthelockisheldbyanotherthreadthenthe
  368. *currentthreadbecomesdisabledforthreadscheduling
  369. *purposesandliesdormantuntiloneofthreethingshappens:
  370. *
  371. *<ul>
  372. *
  373. *<li>Thelockisacquiredbythecurrentthread;or
  374. *
  375. *<li>Someotherthread{@linkplainThread#interruptinterrupts}
  376. *thecurrentthread;or
  377. *
  378. *<li>Thespecifiedwaitingtimeelapses
  379. *
  380. *</ul>
  381. *
  382. *<p>Ifthelockisacquiredthenthevalue{@codetrue}isreturnedand
  383. *thelockholdcountissettoone.
  384. *
  385. *<p>Ifthecurrentthread:
  386. *
  387. *<ul>
  388. *
  389. *<li>hasitsinterruptedstatussetonentrytothismethod;or
  390. *
  391. *<li>is{@linkplainThread#interruptinterrupted}while
  392. *acquiringthelock,
  393. *
  394. *</ul>
  395. *then{@linkInterruptedException}isthrownandthecurrentthreads
  396. *interruptedstatusiscleared.
  397. *
  398. *<p>Ifthespecifiedwaitingtimeelapsesthenthevalue{@codefalse}
  399. *isreturned.Ifthetimeislessthanorequaltozero,themethod
  400. *willnotwaitatall.
  401. *
  402. *<p>Inthisimplementation,asthismethodisanexplicit
  403. *interruptionpoint,preferenceisgiventorespondingtothe
  404. *interruptovernormalorreentrantacquisitionofthelock,and
  405. *overreportingtheelapseofthewaitingtime.
  406. *
  407. *@paramtimeoutthetimetowaitforthelock
  408. *@paramunitthetimeunitofthetimeoutargument
  409. *@return{@codetrue}ifthelockwasfreeandwasacquiredbythe
  410. *currentthread,orthelockwasalreadyheldbythecurrent
  411. *thread;and{@codefalse}ifthewaitingtimeelapsedbefore
  412. *thelockcouldbeacquired
  413. *@throwsInterruptedExceptionifthecurrentthreadisinterrupted
  414. *@throwsNullPointerExceptionifthetimeunitisnull
  415. *
  416. */
  417. publicbooleantryLock(longtimeout,TimeUnitunit)
  418. throwsInterruptedException{
  419. returnsync.tryAcquireNanos(1,unit.toNanos(timeout));
  420. }
  421. /**
  422. *Attemptstoreleasethislock.
  423. *
  424. *<p>Ifthecurrentthreadistheholderofthislockthenthehold
  425. *countisdecremented.Iftheholdcountisnowzerothenthelock
  426. *isreleased.Ifthecurrentthreadisnottheholderofthis
  427. *lockthen{@linkIllegalMonitorStateException}isthrown.
  428. *
  429. *@throwsIllegalMonitorStateExceptionifthecurrentthreaddoesnot
  430. *holdthislock
  431. */
  432. publicvoidunlock(){
  433. sync.release(1);
  434. }
  435. /**
  436. *Returnsa{@linkCondition}instanceforusewiththis
  437. *{@linkLock}instance.
  438. *
  439. *<p>Thereturned{@linkCondition}instancesupportsthesame
  440. *usagesasdothe{@linkObject}monitormethods({@link
  441. *Object#wait()wait},{@linkObject#notifynotify},and{@link
  442. *Object#notifyAllnotifyAll})whenusedwiththebuilt-in
  443. *monitorlock.
  444. *
  445. *<ul>
  446. *
  447. *<li>Ifthislockisnotheldwhenanyofthe{@linkCondition}
  448. *{@linkplainCondition#await()waiting}or{@linkplain
  449. *Condition#signalsignalling}methodsarecalled,thenan{@link
  450. *IllegalMonitorStateException}isthrown.
  451. *
  452. *<li>Whenthecondition{@linkplainCondition#await()waiting}
  453. *methodsarecalledthelockisreleasedand,beforethey
  454. *return,thelockisreacquiredandthelockholdcountrestored
  455. *towhatitwaswhenthemethodwascalled.
  456. *
  457. *<li>Ifathreadis{@linkplainThread#interruptinterrupted}
  458. *whilewaitingthenthewaitwillterminate,an{@link
  459. *InterruptedException}willbethrown,andthethreads
  460. *interruptedstatuswillbecleared.
  461. *
  462. *<li>WaitingthreadsaresignalledinFIFOorder.
  463. *
  464. *<li>Theorderingoflockreacquisitionforthreadsreturning
  465. *fromwaitingmethodsisthesameasforthreadsinitially
  466. *acquiringthelock,whichisinthedefaultcasenotspecified,
  467. *butfor<em>fair</em>locksfavorsthosethreadsthathavebeen
  468. *waitingthelongest.
  469. *
  470. *</ul>
  471. *
  472. *@returntheConditionobject
  473. */
  474. publicConditionnewCondition(){
  475. returnsync.newCondition();
  476. }
  477. /**
  478. *Queriesthenumberofholdsonthislockbythecurrentthread.
  479. *
  480. *<p>Athreadhasaholdonalockforeachlockactionthatisnot
  481. *matchedbyanunlockaction.
  482. *
  483. *<p>Theholdcountinformationistypicallyonlyusedfortestingand
  484. *debuggingpurposes.Forexample,ifacertainsectionofcodeshould
  485. *notbeenteredwiththelockalreadyheldthenwecanassertthat
  486. *fact:
  487. *
  488. *<pre>
  489. *classX{
  490. *ReentrantLocklock=newReentrantLock();
  491. *//...
  492. *publicvoidm(){
  493. *assertlock.getHoldCount()==0;
  494. *lock.lock();
  495. *try{
  496. *//...methodbody
  497. *}finally{
  498. *lock.unlock();
  499. *}
  500. *}
  501. *}
  502. *</pre>
  503. *
  504. *@returnthenumberofholdsonthislockbythecurrentthread,
  505. *orzeroifthislockisnotheldbythecurrentthread
  506. */
  507. publicintgetHoldCount(){
  508. returnsync.getHoldCount();
  509. }
  510. /**
  511. *Queriesifthislockisheldbythecurrentthread.
  512. *
  513. *<p>Analogoustothe{@linkThread#holdsLock}methodforbuilt-in
  514. *monitorlocks,thismethodistypicallyusedfordebuggingand
  515. *testing.Forexample,amethodthatshouldonlybecalledwhile
  516. *alockisheldcanassertthatthisisthecase:
  517. *
  518. *<pre>
  519. *classX{
  520. *ReentrantLocklock=newReentrantLock();
  521. *//...
  522. *
  523. *publicvoidm(){
  524. *assertlock.isHeldByCurrentThread();
  525. *//...methodbody
  526. *}
  527. *}
  528. *</pre>
  529. *
  530. *<p>Itcanalsobeusedtoensurethatareentrantlockisused
  531. *inanon-reentrantmanner,forexample:
  532. *
  533. *<pre>
  534. *classX{
  535. *ReentrantLocklock=newReentrantLock();
  536. *//...
  537. *
  538. *publicvoidm(){
  539. *assert!lock.isHeldByCurrentThread();
  540. *lock.lock();
  541. *try{
  542. *//...methodbody
  543. *}finally{
  544. *lock.unlock();
  545. *}
  546. *}
  547. *}
  548. *</pre>
  549. *
  550. *@return{@codetrue}ifcurrentthreadholdsthislockand
  551. *{@codefalse}otherwise
  552. */
  553. publicbooleanisHeldByCurrentThread(){
  554. returnsync.isHeldExclusively();
  555. }
  556. /**
  557. *Queriesifthislockisheldbyanythread.Thismethodis
  558. *designedforuseinmonitoringofthesystemstate,
  559. *notforsynchronizationcontrol.
  560. *
  561. *@return{@codetrue}ifanythreadholdsthislockand
  562. *{@codefalse}otherwise
  563. */
  564. publicbooleanisLocked(){
  565. returnsync.isLocked();
  566. }
  567. /**
  568. *Returns{@codetrue}ifthislockhasfairnesssettrue.
  569. *
  570. *@return{@codetrue}ifthislockhasfairnesssettrue
  571. */
  572. publicfinalbooleanisFair(){
  573. returnsyncinstanceofFairSync;
  574. }
  575. /**
  576. *Returnsthethreadthatcurrentlyownsthislock,or
  577. *{@codenull}ifnotowned.Whenthismethodiscalledbya
  578. *threadthatisnottheowner,thereturnvaluereflectsa
  579. *best-effortapproximationofcurrentlockstatus.Forexample,
  580. *theownermaybemomentarily{@codenull}evenifthereare
  581. *threadstryingtoacquirethelockbuthavenotyetdoneso.
  582. *Thismethodisdesignedtofacilitateconstructionof
  583. *subclassesthatprovidemoreextensivelockmonitoring
  584. *facilities.
  585. *
  586. *@returntheowner,or{@codenull}ifnotowned
  587. */
  588. protectedThreadgetOwner(){
  589. returnsync.getOwner();
  590. }
  591. /**
  592. *Querieswhetheranythreadsarewaitingtoacquirethislock.Notethat
  593. *becausecancellationsmayoccuratanytime,a{@codetrue}
  594. *returndoesnotguaranteethatanyotherthreadwillever
  595. *acquirethislock.Thismethodisdesignedprimarilyforusein
  596. *monitoringofthesystemstate.
  597. *
  598. *@return{@codetrue}iftheremaybeotherthreadswaitingto
  599. *acquirethelock
  600. */
  601. publicfinalbooleanhasQueuedThreads(){
  602. returnsync.hasQueuedThreads();
  603. }
  604. /**
  605. *Querieswhetherthegiventhreadiswaitingtoacquirethis
  606. *lock.Notethatbecausecancellationsmayoccuratanytime,a
  607. *{@codetrue}returndoesnotguaranteethatthisthread
  608. *willeveracquirethislock.Thismethodisdesignedprimarilyforuse
  609. *inmonitoringofthesystemstate.
  610. *
  611. *@paramthreadthethread
  612. *@return{@codetrue}ifthegiventhreadisqueuedwaitingforthislock
  613. *@throwsNullPointerExceptionifthethreadisnull
  614. */
  615. publicfinalbooleanhasQueuedThread(Threadthread){
  616. returnsync.isQueued(thread);
  617. }
  618. /**
  619. *Returnsanestimateofthenumberofthreadswaitingto
  620. *acquirethislock.Thevalueisonlyanestimatebecausethenumberof
  621. *threadsmaychangedynamicallywhilethismethodtraverses
  622. *internaldatastructures.Thismethodisdesignedforusein
  623. *monitoringofthesystemstate,notforsynchronization
  624. *control.
  625. *
  626. *@returntheestimatednumberofthreadswaitingforthislock
  627. */
  628. publicfinalintgetQueueLength(){
  629. returnsync.getQueueLength();
  630. }
  631. /**
  632. *Returnsacollectioncontainingthreadsthatmaybewaitingto
  633. *acquirethislock.Becausetheactualsetofthreadsmaychange
  634. *dynamicallywhileconstructingthisresult,thereturned
  635. *collectionisonlyabest-effortestimate.Theelementsofthe
  636. *returnedcollectionareinnoparticularorder.Thismethodis
  637. *designedtofacilitateconstructionofsubclassesthatprovide
  638. *moreextensivemonitoringfacilities.
  639. *
  640. *@returnthecollectionofthreads
  641. */
  642. protectedCollection<Thread>getQueuedThreads(){
  643. returnsync.getQueuedThreads();
  644. }
  645. /**
  646. *Querieswhetheranythreadsarewaitingonthegivencondition
  647. *associatedwiththislock.Notethatbecausetimeoutsand
  648. *interruptsmayoccuratanytime,a{@codetrue}returndoes
  649. *notguaranteethatafuture{@codesignal}willawakenany
  650. *threads.Thismethodisdesignedprimarilyforusein
  651. *monitoringofthesystemstate.
  652. *
  653. *@paramconditionthecondition
  654. *@return{@codetrue}ifthereareanywaitingthreads
  655. *@throwsIllegalMonitorStateExceptionifthislockisnotheld
  656. *@throwsIllegalArgumentExceptionifthegivenconditionis
  657. *notassociatedwiththislock
  658. *@throwsNullPointerExceptioniftheconditionisnull
  659. */
  660. publicbooleanhasWaiters(Conditioncondition){
  661. if(condition==null)
  662. thrownewNullPointerException();
  663. if(!(conditioninstanceofAbstractQueuedSynchronizer.ConditionObject))
  664. thrownewIllegalArgumentException("notowner");
  665. returnsync.hasWaiters((AbstractQueuedSynchronizer.ConditionObject)condition);
  666. }
  667. /**
  668. *Returnsanestimateofthenumberofthreadswaitingonthe
  669. *givenconditionassociatedwiththislock.Notethatbecause
  670. *timeoutsandinterruptsmayoccuratanytime,theestimate
  671. *servesonlyasanupperboundontheactualnumberofwaiters.
  672. *Thismethodisdesignedforuseinmonitoringofthesystem
  673. *state,notforsynchronizationcontrol.
  674. *
  675. *@paramconditionthecondition
  676. *@returntheestimatednumberofwaitingthreads
  677. *@throwsIllegalMonitorStateExceptionifthislockisnotheld
  678. *@throwsIllegalArgumentExceptionifthegivenconditionis
  679. *notassociatedwiththislock
  680. *@throwsNullPointerExceptioniftheconditionisnull
  681. */
  682. publicintgetWaitQueueLength(Conditioncondition){
  683. if(condition==null)
  684. thrownewNullPointerException();
  685. if(!(conditioninstanceofAbstractQueuedSynchronizer.ConditionObject))
  686. thrownewIllegalArgumentException("notowner");
  687. returnsync.getWaitQueueLength((AbstractQueuedSynchronizer.ConditionObject)
  688. condition);
  689. }
  690. /**
  691. *Returnsacollectioncontainingthosethreadsthatmaybe
  692. *waitingonthegivenconditionassociatedwiththislock.
  693. *Becausetheactualsetofthreadsmaychangedynamicallywhile
  694. *constructingthisresult,thereturnedcollectionisonlya
  695. *best-effortestimate.Theelementsofthereturnedcollection
  696. *areinnoparticularorder.Thismethodisdesignedto
  697. *facilitateconstructionofsubclassesthatprovidemore
  698. *extensiveconditionmonitoringfacilities.
  699. *
  700. *@paramconditionthecondition
  701. *@returnthecollectionofthreads
  702. *@throwsIllegalMonitorStateExceptionifthislockisnotheld
  703. *@throwsIllegalArgumentExceptionifthegivenconditionis
  704. *notassociatedwiththislock
  705. *@throwsNullPointerExceptioniftheconditionisnull
  706. */
  707. protectedCollection<Thread>getWaitingThreads(Conditioncondition){
  708. if(condition==null)
  709. thrownewNullPointerException();
  710. if(!(conditioninstanceofAbstractQueuedSynchronizer.ConditionObject))
  711. thrownewIllegalArgumentException("notowner");
  712. returnsync.getWaitingThreads((AbstractQueuedSynchronizer.ConditionObject)
  713. condition);
  714. }
  715. /**
  716. *Returnsastringidentifyingthislock,aswellasitslockstate.
  717. *Thestate,inbrackets,includeseithertheString{@code"Unlocked"}
  718. *ortheString{@code"Lockedby"}followedbythe
  719. *{@linkplainThread#getNamename}oftheowningthread.
  720. *
  721. *@returnastringidentifyingthislock,aswellasitslockstate
  722. */
  723. publicStringtoString(){
  724. Threado=sync.getOwner();
  725. returnsuper.toString()+((o==null)?
  726. "[Unlocked]":
  727. "[Lockedbythread"+o.getName()+"]
  728. ");
  729. }
  730. }
复制代码
<p>
有了这样一个呼声:让java代替C语言成为基本语言。这些足以说明java简单易学的这个优点。其次,java的功能强大,前面我也提到了,EJB3.0的推出使java成为了大型项目的首选。
作者: admin    时间: 2015-1-20 12:44
那么我书也看了,程序也做了,别人问我的问题我都能解决了,是不是就成为高手了呢?当然没那么简单,这只是万里长征走完了第一步。不信?那你出去接一个项目,你知道怎么下手吗,你知道怎么设计吗,你知道怎么组织人员进行开发吗?你现在脑子里除了一些散乱的代码之外,可能再没有别的东西了吧!
作者: 不帅    时间: 2015-1-20 21:10
不过,每次的执行编译后的字节码需要消耗一定的时间,这同时也在一定程度上降低了 Java 程序的运行效率。
作者: 小女巫    时间: 2015-1-21 16:35
其实说这种话的人就如当年小日本号称“三个月拿下中国”一样大言不惭。不是Tomjava泼你冷水,你现在只是学到了Java的骨架,却还没有学到Java的精髓。接下来你得研究设计模式了。
作者: 灵魂腐蚀    时间: 2015-1-26 21:00
至于JDBC,就不用我多说了,你如果用java编过存取数据库的程序,就应该很熟悉。还有,如果你要用Java编发送电子邮件的程序,你就得看看Javamail 了。
作者: 莫相离    时间: 2015-2-4 20:22
至于JDBC,就不用我多说了,你如果用java编过存取数据库的程序,就应该很熟悉。还有,如果你要用Java编发送电子邮件的程序,你就得看看Javamail 了。
作者: 飘灵儿    时间: 2015-2-10 06:26
你就该学一学Servlet了。Servlet就是服务器端小程序,他负责生成发送给客户端的HTML文件。JSP在执行时,也是先转换成Servlet再运行的。虽说JSP理论上可以完全取代Servlet,这也是SUN推出JSP的本意,可是Servlet用来控制流程跳转还是挺方便的,也令程序更清晰。接下来你应该学习一下Javabean了,可能你早就看不管JSP在HTML中嵌Java代码的混乱方式了,这种方式跟ASP又有什么区别呢?
作者: 透明    时间: 2015-2-28 23:02
学Java必读的两个开源程序就是Jive和Pet Store.。 Jive是国外一个非常著名的BBS程序,完全开放源码。论坛的设计采用了很多先进的技术,如Cache、用户认证、Filter、XML等,而且论坛完全屏蔽了对数据库的访问,可以很轻易的在不同数据库中移植。论坛还有方便的安装和管理程序,这是我们平时编程时容易忽略的一部份(中国程序员一般只注重编程的技术含量,却完全不考虑用户的感受,这就是我们与国外软件的差距所在)。
作者: 飘飘悠悠    时间: 2015-3-10 09:59
任职于太阳微系统的詹姆斯·高斯林等人于1990年代初开发Java语言的雏形,最初被命名为Oak,目标设置在家用电器等小型系统的程序语言
作者: 小妖女    时间: 2015-3-17 06:10
Java是一个纯的面向对象的程序设计语言,它继承了 C++语言面向对象技术的核心。Java舍弃了C ++语言中容易引起错误的指针(以引用取代)、运算符重载(operator overloading)
作者: 活着的死人    时间: 2015-3-23 22:58
是一种使网页(Web Page)由静态(Static)转变为动态(Dynamic)的语言




欢迎光临 仓酷云 (http://ckuyun.com/) Powered by Discuz! X3.2