公平锁和非公平锁

protected  final  boolean  tryAcquire( int  acquires) {
     final  Thread current = Thread.currentThread();
     int  c = getState();
     //状态为0,说明当前没有线程占有锁
     if  (c ==  0 ) {
         //如果当前线程是等待队列的第一个或者等待队列为空,则通过cas指令设置state为1,当前线程获得锁
         if  (isFirst(current) &&
             compareAndSetState( 0 , acquires)) {
             setExclusiveOwnerThread(current);
             return  true ;
         }
     }
//如果当前线程本身就持有锁,那么叠加状态值,持续获得锁
     else  if  (current == getExclusiveOwnerThread()) {
         int  nextc = c + acquires;
         if  (nextc <  0 )
             throw  new  Error( "Maximum lock count exceeded" );
         setState(nextc);
         return  true ;
      }
      //以上条件都不满足,那么线程进入等待队列。
      return  false ;
} 
final boolean nonfairTryAcquire(int acquires) {
            final Thread current = Thread.currentThread();
            int c = getState();
            if (c == 0) {
                //如果当前没有线程占有锁,当前线程直接通过cas指令占有锁,管他等待队列,就算自己排在队尾也是这样
                if (compareAndSetState(0, acquires)) {
                    setExclusiveOwnerThread(current);
                    return true;
                }
            }
            else if (current == getExclusiveOwnerThread()) {
                int nextc = c + acquires;
                if (nextc < 0) // overflow
                    throw new Error("Maximum lock count exceeded");
                setState(nextc);
                return true;
            }
            return false;
        }

       公平性与否是针对获取锁而言的,如果一个锁是公平的,那么锁的获取顺序就应该符合请求的绝对时间顺序,也就是FIFO。

       公平性锁每次都是从同步队列中的第一个节点获取到锁,而非公平性锁则会出现一个线程连续获取锁的情况。非公平性锁虽然可能造成线程“饥饿”,但极少的线程切换,能保证了更大的吞吐量。

猜你喜欢

转载自aiyoul.iteye.com/blog/2346844