// 共享模式下非公平策略获取 finalintnonfairTryAcquireShared(int acquires){ //无限循环 for (;;) { // 获取许可数 int available = getState(); //剩余的许可 int remaining = available - acquires;
// 共享模式下进行释放 protectedfinalbooleantryReleaseShared(int releases){ //无限循环 for (;;) { //释放许可 int current = getState(); // 可用的许可 int next = current + releases; if (next < current) // overflow thrownew Error("Maximum permit count exceeded"); //CAS设置许可数 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; } } }