CountDownLatch使用synchronized、notifyAll、wait實現

爲了加上對CountDownLatch的理解,自己DIY使用synchronized、notifyAll、wait實現CountDownLatch的功能,下面直接貼代碼了。如有問題,歡迎大家指出

public class CountDownLatchDiyTest {
    
    public static void main(String[] args) throws Exception {
        int n = 1000;
        final CountDownLatchDiy startSignal = new CountDownLatchDiy(1);
        final CountDownLatchDiy doneSignal = new CountDownLatchDiy(n);
        ExecutorService fixedThreadPool = Executors.newFixedThreadPool(100);
        for (int i = 0; i < n; i++) {
            fixedThreadPool.execute(
                new Thread("任務" + String.valueOf(i)) {
                    public void run() {
                        try {
                            startSignal.await();
                            System.out.println(this.getName() + " thread start");
                            Thread.sleep(random(100));
                            System.out.println(this.getName() + " thread over");
                            doneSignal.countDown();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
        }
        System.out.println("main thread start");
        startSignal.countDown();
        Thread.sleep(random(100));
        doneSignal.await();
        System.out.println("main thread over");
        fixedThreadPool.shutdown();
    }

    static class CountDownLatchDiy {
        private int count;

        CountDownLatchDiy(int c) {
            this.count = c;
        }

        public synchronized void countDown() {
            if (count > 0) {
                count = count - 1;
                notifyAll();
                return;
            }

            throw new RuntimeException(Thread.currentThread().getName() + " count <= 0 .");
        }

        public synchronized void await() throws InterruptedException {
            while (count > 0) {
                wait();
            }
        }
    }

    static long random(long max) {
        return 1 + new Double(Math.random() * max).longValue();
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章