CountDownLatch使用synchronized、notifyAll、wait实现

本文分享了一种使用synchronized、notifyAll、wait等方法手工实现CountDownLatch功能的代码示例,通过创建自定义的CountDownLatchDiy类,演示了如何在多线程环境下控制线程的等待和唤醒,确保所有任务完成后再继续执行后续操作。
摘要由CSDN通过智能技术生成

为了加上对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();
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值