概念:
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(); } }
下面,我们来看一看结果: