CountDownLatch的用法

CountDownLatch一个同步辅助工具,允许一个或多个线程等待其他线程中执行的一组操作完成。类似的场景有考试,比如老师必须要等学生交完试卷才能离开考场

代码案例


public class Exam {

    public static void main(String[] args) throws InterruptedException {

        //学生人数
        int studentNum = 50;

        //完成标记
        CountDownLatch doneSignal = new CountDownLatch(studentNum);
        //开始标记,用于一开始学生必须等待老师发放试卷,才能答题后交卷
        CountDownLatch startSignal = new CountDownLatch(1);

        new Thread(() -> {
            try {
                //假设学生先来
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            //业务原子性,不然打印会乱序
            synchronized (startSignal) {
                startSignal.countDown();
                System.out.println(Thread.currentThread().getName() + ": " + "考试开始,发放试卷,学生开始答题!");
            }
            try {
                doneSignal.await();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println("考试结束,学生已经全部交卷");
        }, "Teacher").start();

        new Thread(() -> {
            //生成50个线程,每个线程代表一个学生,
            for (int num = 1; num <= studentNum; num++) {
                new Thread(() -> {
                    try {
                        startSignal.await();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    //业务原子性,不然打印会乱序
                    synchronized (startSignal) {
                        doneSignal.countDown();
                        System.out.println(Thread.currentThread().getName() + ": " + "交卷");
                    }
                }, "Student-" + num).start();
            }
        }).start();

    }


}

这里需要注意的是为什么要用两CountDownLatch配合使用,代码里面的stratSingal的作用是学生必须要等老师发放了试卷才能答题交卷,如果注释了的话,就有可能是学生先交试卷,老师后发放试卷.在main线程中 这两个线程的执行顺序不一定是前后顺序,当然老师和学生都有可能先来到考场

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
CountDownLatch是Java中提供的一个同步工具类,它可以用来控制一个或多个线程等待多个线程的操作完成。 CountDownLatch用法如下: 1. 创建一个CountDownLatch对象,指定需要等待的线程数。 ``` CountDownLatch latch = new CountDownLatch(5); ``` 2. 每个需要等待的线程执行完后调用CountDownLatch的countDown方法减少计数器。 ``` latch.countDown(); ``` 3. 等待所有线程执行完毕后,调用CountDownLatch的await方法进行等待。 ``` latch.await(); ``` 4. 在所有线程执行完毕后,主线程或其他线程可以继续执行自己的操作。 示例代码: ``` import java.util.concurrent.CountDownLatch; public class CountDownLatchDemo { public static void main(String[] args) throws InterruptedException { CountDownLatch latch = new CountDownLatch(5); for (int i = 0; i < 5; i++) { new Thread(() -> { System.out.println(Thread.currentThread().getName() + " is working..."); try { // 模拟线程执行时间 Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + " done"); latch.countDown(); }).start(); } System.out.println("Waiting for all threads to finish..."); latch.await(); System.out.println("All threads have finished, continue to execute the main thread."); } } ``` 运行结果: ``` Waiting for all threads to finish... Thread-0 is working... Thread-2 is working... Thread-1 is working... Thread-3 is working... Thread-4 is working... Thread-1 done Thread-3 done Thread-0 done Thread-2 done Thread-4 done All threads have finished, continue to execute the main thread. ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值