CountDownLatch
在CountDownLatch类里面有两个方法
一个是await()字面意思是等待的一次,他和sleep()方法的区别就是sellp()会自己醒过来,而await()方法需要另一个方法来唤醒,就是countDown()。
演示代码
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
/**
* @author Mxhlin
* @Email [email protected]
* @Date 2022/10/01/8:37
* @Version
* @Description 门闩案例
*/
public class T3 {
CountDownLatch latch = new CountDownLatch(1);
List<String> list = new ArrayList<>();
void add(){
String name = Thread.currentThread().getName();
System.out.printf("%s线程启动...",name);
while (true){
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
String time = "tiem"+list.size();
list.add(time);
if (list.size() == 5)latch.countDown();
System.out.println(time);
// if (list.size()>9){
// break;
// }
}
}
void cheak(){
String t = Thread.currentThread().getName();
System.out.printf("%s线程启动",t);
try {
latch.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.printf("%s线程:到第五个元素了%n",t);
}
public static void main(String[] args) {
T3 t = new T3();
new Thread(t::add,"工作").start();
new Thread(t::cheak,"统计").start();
}
}
两个线程同时同时开始cheak这个线程执行到latch.await()这个方法时会停止,等待唤醒,而add方法会判断执行latch.await()来唤醒await;