主要方法:countDown()、await() downLatch.countDown(); //数量-1 downLatch.await();//等待计数器归零,然后再往下执行 每次线程调用countDown()数量-1,假设计数器变成0,downLatch.await()就会被唤醒,继续执行!
如果没有使用await方法,那么主线程其实是一直在跑的,所以还没等上面的六个线程跑完,主线程关门就已经输出了。
package com.han.demo01;
import java.util.concurrent.CountDownLatch;
public class countDownLatch {
public static void main(String[] args) throws InterruptedException {
CountDownLatch downLatch = new CountDownLatch(6);
for (int i = 1; i <= 6; i++) {
new Thread(() -> {
System.out.println(Thread.currentThread().getName() + "出去了");
downLatch.countDown();
}, String.valueOf(i)).start();
}
System.out.println("主线程关门!");
}
}
结果:
使用await方法,那么主线程在countdown计数没有减到0的情况下,await方法后面的内容无法执行,必须等待。
package com.han.demo01;
import java.util.concurrent.CountDownLatch;
public class countDownLatch {
public static void main(String[] args) throws InterruptedException {
CountDownLatch downLatch = new CountDownLatch(6);
for (int i = 1; i <= 6; i++) {
new Thread(() -> {
System.out.println(Thread.currentThread().getName() + "出去了");
downLatch.countDown();
}, String.valueOf(i)).start();
}
downLatch.await();
System.out.println("主线程关门!");
}
}
结果:
|