//继承自AQS abstract static class Sync extends AbstractQueuedSynchronizer {
//由具体的子类实现,即公平和非公平的有不同实现 abstract void lock();
//非公平的尝试获取 final boolean nonfairTryAcquire(int acquires) { //当前线程 final Thread current = Thread.currentThread(); //当前AQS同步器的状态 int c = getState(); //状态为0,说明没有人获取锁 if (c == 0) { //尝试获取,获取成功设为独占模式 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; } //尝试释放 protected final boolean tryRelease(int releases) { int c = getState() - releases; if (Thread.currentThread() != getExclusiveOwnerThread()) throw new IllegalMonitorStateException(); boolean free = false; if (c == 0) { free = true; setExclusiveOwnerThread(null); } setState(c); return free; } //是否是独占 protected final boolean isHeldExclusively() { // While we must in general read state before owner, // we don't need to do so to check if current thread is owner return getExclusiveOwnerThread() == Thread.currentThread(); } final ConditionObject newCondition() { return new ConditionObject(); }
// Methods relayed from outer class //获取持有者线程 final Thread getOwner() { return getState() == 0 ? null : getExclusiveOwnerThread(); } //获取重入数 final int getHoldCount() { return isHeldExclusively() ? getState() : 0; } //是否锁了 final boolean isLocked() { return getState() != 0; }
// private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException { s.defaultReadObject(); setState(0); // reset to unlocked state } }
//查询是否有线程正在等待给定的Condition public boolean hasWaiters(Condition condition) { if (condition == null) throw new NullPointerException(); if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject)) throw new IllegalArgumentException("not owner"); return sync.hasWaiters((AbstractQueuedSynchronizer.ConditionObject)condition); }
//得到正在等待一个Condition的队列的长度 public int getWaitQueueLength(Condition condition) { if (condition == null) throw new NullPointerException(); if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject)) throw new IllegalArgumentException("not owner"); return sync.getWaitQueueLength((AbstractQueuedSynchronizer.ConditionObject)condition); }
//获取所有的等待某个Condition的线程集合 protected Collection<Thread> getWaitingThreads(Condition condition) { if (condition == null) throw new NullPointerException(); if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject)) throw new IllegalArgumentException("not owner"); return sync.getWaitingThreads((AbstractQueuedSynchronizer.ConditionObject)condition); }