← 中文资源

简体中文版本

AQS 自定义共享闩锁

继承 AbstractQueuedSynchronizer 实现 tryAcquireShared 与 tryReleaseShared:state 减到零才放行共享队列上的等待者,这就是 CountDownLatch 的内核机制。

阅读英文原文

实现说明

底层就是类 GroupGate、SharedLatch和函数 tryAcquireShared、tryReleaseShared。 这个示例中仅有的重复出现在 for (;;) 里。

使用要点

  • 每一步打印都带着自己的标签:passed the gate、remaining:。

常见问题

运行「AQS 自定义共享闩锁」会打印什么?

文件本身就是完整程序,直接运行——输出行带有 passed the gate、remaining: 这类标签。

主要签名是 protected int tryAcquireShared(int unused)

核心语句

Thread second = new Thread(waiter, "second");
Thread first = new Thread(waiter, "first");
return count - 1 == 0; // 归零时唤醒共享队列
}

代码示例

import java.util.concurrent.locks.AbstractQueuedSynchronizer;

public class GroupGate {

    // a custom shared latch: state counts down, shared queue wakes all waiters at zero
    static final class SharedLatch extends AbstractQueuedSynchronizer {
        SharedLatch(int count) {
            setState(count);
        }

        int remaining() {
            return getState();
        }

        @Override
        protected int tryAcquireShared(int unused) {
            return getState() == 0 ? 1 : -1;
        }

        @Override
        protected boolean tryReleaseShared(int unused) {
            for (;;) {
                int count = getState();
                if (count == 0) {
                    return false;
                }
                if (compareAndSetState(count, count - 1)) {
                    return count - 1 == 0; // 归零时唤醒共享队列
                }
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        SharedLatch latch = new SharedLatch(2);
        Runnable waiter = () -> {
            try {
                latch.acquireSharedInterruptibly(1);
                System.out.println("passed the gate");
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        };
        Thread first = new Thread(waiter, "first");
        Thread second = new Thread(waiter, "second");
        first.start();
        second.start();
        Thread.sleep(50);
        System.out.println("remaining: " + latch.remaining());
        latch.releaseShared(1);
        latch.releaseShared(1);
        first.join();
        second.join();
    }
}