手写CountDownLatch
手写CountDownLatch思路
1. 设置aqs类中的状态为2;
2. 调用await方法,让当前线程变为阻塞
3. 调用countDown方法的时候 状态-1,如果状态=0的情况下,则唤醒刚才阻塞的线程
public class MyCountDownLatch { private Sync sync; private MyCountDownLatch(int count) { sync = new Sync(count); } public void await() { sync.acquireShared(1); } public void countDown() { sync.releaseShared(1); } class Sync extends AbstractQueuedSynchronizer { public Sync(int count) { setState(count); } @Override protected int tryAcquireShared(int arg) { return getState() > 0 ? -1 : 1; } @Override protected boolean tryReleaseShared(int arg) { for (; ; ) { int oldState = getState(); int newSate = oldState - arg; if (compareAndSetState(oldState, newSate)) { return true; } } } } public static void main(String[] args) throws InterruptedException { MyCountDownLatch myCountDownLatch = new MyCountDownLatch(2); new Thread(() -> { System.out.println(Thread.currentThread().getName() + "你好1"); mayiktCountDownLatch.await(); System.out.println(Thread.currentThread().getName() + "你好2"); }).start(); myCountDownLatch.countDown(); myCountDownLatch.countDown(); ; } }
早年同窗始相知,三载瞬逝情却萌。年少不知愁滋味,犹读红豆生南国。别离方知相思苦,心田红豆根以生。