public void acquire() throws InterruptedException { sync.acquireSharedInterruptibly(1);//可以被中断的获锁方法 }
从信号量获取一个许可,如果无可用许可前将一直阻塞等待。
acquireSharedInterruptibly(int arg)方法
1 2 3 4 5 6 7
public final void acquireSharedInterruptibly(int arg) throws InterruptedException { if (Thread.interrupted())//如果当前线程被中断就抛出异常 throw new InterruptedException(); if (tryAcquireShared(arg) < 0)//尝试获得异常 doAcquireSharedInterruptibly(arg);//获锁失败放进等待队列 }
tryAcquireShared(int arg)方法
非公平锁实现
1 2 3
protected int tryAcquireShared(int acquires) { return nonfairTryAcquireShared(acquires); }
1 2 3 4 5 6 7 8 9 10
final int nonfairTryAcquireShared(int acquires) { for (;;) { int available = getState();//获得可用锁数量 int remaining = available - acquires; //如果没有锁了就直接返回否则尝试获得锁资源 if (remaining < 0 || compareAndSetState(available, remaining)) return remaining; } }
公平锁实现
1 2 3 4 5 6 7 8 9 10 11
protected int tryAcquireShared(int acquires) { for (;;) { if (hasQueuedPredecessors())//公平策略就是判断当前节点是否有前驱节点(跟上面的ReentrantLock的公平策略一样的) return -1; int available = getState(); int remaining = available - acquires; if (remaining < 0 || compareAndSetState(available, remaining)) return remaining; } }
public final boolean releaseShared(int arg) { if (tryReleaseShared(arg))//尝试释放锁 { doReleaseShared(); return true; } return false; }
tryReleaseShared(int releases)方法
1 2 3 4 5 6 7 8 9 10
protected final boolean tryReleaseShared(int releases) { for (;;) { int current = getState();//获得队列中可用锁数量 int next = current + releases; if (next < current) // overflow throw new Error("Maximum permit count exceeded"); if (compareAndSetState(current, next))//尝试设置数量 return true; } }