首页 > 代码库 > AbstractQueuedSynchronizer 应用

AbstractQueuedSynchronizer 应用

一。ReentrantLock

public boolean tryLock()

Acquires the lock only if it is not held by another thread at the time of invocation.

Acquires the lock if it is not held by another thread and returns immediately with the value true, setting the lock hold count to one.

Even when this lock has been set to use a fair ordering policy, a call to tryLock() will immediately acquire the lock if it is available,

whether or not other threads are currently waiting for the lock. This "barging" behavior can be useful in certain circumstances, even

though it breaks fairness. If you want to honor the fairness setting for this lock, then use tryLock(0, TimeUnit.SECONDS) which is

almost equivalent (it also detects interruption).

If the current thread already holds this lock then the hold count is incremented by one and the method returns true.

If the lock is held by another thread then this method will return immediately with the value false.

 

    public boolean tryLock() {        return sync.nonfairTryAcquire(1);    }

默认使用非公平锁

        final boolean nonfairTryAcquire(int acquires) {            final Thread current = Thread.currentThread();            int c = getState();                                    //状态值表示锁获取操作的次数,0是第一次获取            if (c == 0) {                if (compareAndSetState(0, acquires)) {                    setExclusiveOwnerThread(current);              //保存第一次获取操作的线程                    return true;                }            }else if (current == getExclusiveOwnerThread()) {       //状态值不为1,且当前线程是先前保存的线程,则锁获取操作的次数加1                int nextc = c + acquires;                if (nextc < 0) // overflow                    throw new Error("Maximum lock count exceeded");                setState(nextc);                return true;            }            return false;        }

 

AbstractQueuedSynchronizer 应用