1、非公平锁不能保证锁的获取是按照请求锁的顺序进行的。这可能会导致某个或某些线程永远得不到锁。
2、CPU唤醒线程的费用可以降低,整体吞吐效率会很高。但是可能会有线程长时间甚至永远得不到锁,导致饿死。
实例
/** *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.Don'tgrantaccessunless *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; } }原文来自:https://www.py.cn
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END
暂无评论内容