• Java多线程_同步工具CountDownLatch


    概念:
    CountDownLatch是多线程里面一个类似于计数器的高级同步工具,它的初始值代表线程的数量,当一个线程完成了任务后,CountDownLatch的值就减1,当值为0的时候,代表所有线程完成了任务,然后等待的线程可以开始自己的任务。

    方法:
    这里主要涉及到两个核心的方法:

    • await():线程响应中断,进入等待状态。
    • countDown():减1操作,CountDownLatch的值减1。

    示例:

    import java.util.Random;
    import java.util.concurrent.CountDownLatch;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    
    /*
     * 模拟考试过程:学生等待老师发卷,老师发完卷学生答卷,老师等待学生交卷,等到学生全部交卷,老师离开
     */
    public class CountDownLatchDemo implements Runnable {
        static CountDownLatch teacher = new CountDownLatch(1);
        static CountDownLatch student = new CountDownLatch(3);
        static ExecutorService service = Executors.newCachedThreadPool();
    
        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName() + "等待发卷");
            try {
                teacher.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "开始答卷");
            try {
                Thread.sleep(new Random().nextInt(1000));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "交卷");
            student.countDown();
        }
    
        public static void main(String[] args) {
            CountDownLatchDemo cdld = new CountDownLatchDemo();
            for (int i = 0; i < 3; i++) {
                service.execute(cdld);
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e1) {
                e1.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "开始发卷");
            try {
                Thread.sleep(200);
            } catch (InterruptedException e1) {
                e1.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "等待交卷");
            teacher.countDown();
            try {
                student.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "收齐试卷,准备离开");
            service.shutdown();
        }
    }

    下面,我们来看一看结果:

  • 相关阅读:
    BlackBerry Localiztion Websites
    BlackBerry device debug
    (收藏)Android VoIP
    How to access the folder of Android
    listView高度控制 底部tabhost标签 用android:layout_below="@+id/tab_all"
    自定义TabHost,TabWidget样式 .
    点击TextView 弹出复制选项
    如何实现验证两次输入的密码是否一致
    Android 获取SDCard上图片和视频的缩略图
    去掉activity(tabhost )顶部的gradient 黑线 横线 阴影
  • 原文地址:https://www.cnblogs.com/ericz2j/p/10295535.html
Copyright © 2020-2023  润新知