/** * 非公平获取 */ finalintnonfairTryAcquireShared(int acquires){ for (;;) { int available = getState(); int remaining = available - acquires; if (remaining < 0 || compareAndSetState(available, remaining)) return remaining; } }
protectedfinalbooleantryReleaseShared(int releases){ for (;;) { int current = getState(); int next = current + releases; if (next < current) // overflow thrownew Error("Maximum permit count exceeded"); if (compareAndSetState(current, next)) returntrue; } }
finalvoidreducePermits(int reductions){ for (;;) { int current = getState(); int next = current - reductions; if (next > current) // underflow thrownew Error("Permit count underflow"); if (compareAndSetState(current, next)) return; } }
finalintdrainPermits(){ for (;;) { int current = getState(); if (current == 0 || compareAndSetState(current, 0)) return current; } } }
protectedinttryAcquireShared(int acquires){ for (;;) { // 首节点才有机会执行 if (hasQueuedPredecessors()) return -1; int available = getState(); int remaining = available - acquires; if (remaining < 0 || compareAndSetState(available, remaining)) return remaining; } } }