手写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();
        ;
    }

}

 

posted @ 2024-07-25 14:02  山河永慕~  阅读(8)  评论(0编辑  收藏  举报