美文网首页
CountDownLatch用法

CountDownLatch用法

作者: jsjack_wang | 来源:发表于2018-01-23 13:53 被阅读0次
    1.简介(具体查一查API)
        同步辅助类,在完成一组正在其他线程中执行的操作之前,它允许一个或多个线程一直等待。
        说白了就是一组线程或一个线程等待另一组线程。
    
    2.举个简单的小栗子
        比如考试,首先等待所有学生进场,监考老师发试卷等,等老师说考试开始,所有人答题。所有人答题完成,考试结束。
    
    3.代码实现
    public class CountDownLatchDemo {
        private static final int TEACHER_COUNT = 1;
        private static final int STUDENT_COUNT = 5;
    
        public static void main(String[] args) {
            CountDownLatch teacher = new CountDownLatch(TEACHER_COUNT);
            CountDownLatch students = new CountDownLatch(STUDENT_COUNT);
    
            // 学生入场
            for (int index = 0; index < STUDENT_COUNT; index ++) {
                new Thread(new Test(teacher, students)).start();
            }
    
            System.out.println("发试卷");
    
            try {
                teacher.countDown();    // 老师说答题开始
                students.await();   // 等待学生做完题目
                System.out.println("所有学生都已经完成答题");
                System.out.println("考试结束");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
    
    
        }
    }
    
    class Test implements Runnable {
        private CountDownLatch teacher;
        private CountDownLatch students;
    
        public Test(CountDownLatch teacher, CountDownLatch students) {
            this.teacher = teacher;
            this.students = students;
        }
    
        @Override
        public void run() {
            try {
                this.teacher.await();
                answer();
                this.students.countDown();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        private void answer() throws Exception {
            Thread.sleep(1000);
            System.out.println("在紧张答题中 ThreadId:" + Thread.currentThread().getId());
        }
    }
    
    4.总结
    编程就要多写,多看文档,多思考,个人经验

    相关文章

      网友评论

          本文标题:CountDownLatch用法

          本文链接:https://www.haomeiwen.com/subject/ddjsaxtx.html