发布时间:2022-02-24 文章分类:Java知识 投稿人:优优 字号: 默认 | | 超大 打印

632

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;