首页 > 编程语言 >java非公平锁如何理解

java非公平锁如何理解

时间:2022-11-02 14:35:58浏览次数:40  
标签:return int Sync 理解 static 公平 java final acquires

  1、非公平锁不能保证锁的获取是按照请求锁的顺序进行的。这可能会导致某个或某些线程永远得不到锁。

  2、CPU唤醒线程的费用可以降低,整体吞吐效率会很高。但是可能会有线程长时间甚至永远得不到锁,导致饿死。

  实例

    /**
     * Sync object for non-fair locks
     */
    static final class NonfairSync extends Sync {
        private static final long serialVersionUID = 7316153563782823691L;
 
        /**
         * Performs lock.  Try immediate barge, backing up to normal
         * acquire on failure.
         */
        final void lock() {
            if (compareAndSetState(0, 1))
                setExclusiveOwnerThread(Thread.currentThread());
            else
                acquire(1);
        }
 
        protected final boolean tryAcquire(int acquires) {
            return nonfairTryAcquire(acquires);
        }
    }
 
    /**
     * Sync object for fair locks
     */
    static final class FairSync extends Sync {
        private static final long serialVersionUID = -3000897897090466540L;
 
        final void lock() {
            acquire(1);
        }
 
        /**
         * Fair version of tryAcquire.  Don't grant access unless
         * recursive call or no waiters or is first.
         */
        protected final boolean tryAcquire(int acquires) {
            final Thread current = Thread.currentThread();
            int c = getState();
            if (c == 0) {
                if (!hasQueuedPredecessors() &&
                    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;
        }
    }

  以上就是java非公平锁的介绍,希望对大家有所帮助。

标签:return,int,Sync,理解,static,公平,java,final,acquires
From: https://www.cnblogs.com/huakexiaopeng/p/16850907.html

相关文章