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.总结
编程就要多写,多看文档,多思考,个人经验
网友评论