手寫CountDownLatch

山河永慕~發表於2024-07-25
手寫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();
        ;
    }

}

相關文章