You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

11 lines
949 B

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

CountDownLatch让一个或多个线程在运行过程中的某个时间点能停下来等待其他的一些线程完成某些任务后再继续运行
CountDownLatch的构造函数接收一个 int 型参数作为计数器例如想让N任务完成之后才能继续执行创建CountDownLatch时传入参数N
需要等待的线程会调用CountDownLatch的await方法该线程就会阻塞直到计数器的值减为0而达到自己预期的线程会调用CountDownLatch的countDown()方法计数器N的值减1。由于countDown方法可以在任何地方调用所以计数器N既可以代表N个线程也可以是一个线程的N个执行步骤。代表多个线程时只需要将这个CountDownLatch的引用传到线程里面即可。
如下图所示使用CountDownLatch 强制线程等待可以实现每次只处理N条数据的效果而不是一直提交数据给线程池
![[Pasted image 20240530123021.png]]