倒计时器?设定计数,使用await阻塞,使用countDown计数减1,直到计数减为0,所有await阻塞结束并往下执行。类似go语言里的WaitGroup,CountDownLatch不能重复利用。
Demo:
/**
* 2019年8月9日上午10:04:03
*/
package testThreadUtil.testCountDownLatch;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
/**
* @author XWF
*
*/
public class TestCountDownLatch {
private static CountDownLatch countDownLatch = new CountDownLatch(3);//设定计数(只能使用一次不能重用)
/**
* @param args
*/
public static void main(String[] args) {
waitThread();
threadRun(1);
threadRun(2);
threadRun(3);
}
public static void waitThread() {
new Thread(() -> {
System.out.println("run wait thread");
System.out.println("起始计数:" + countDownLatch.getCount());
try {
countDownLatch.await(1, TimeUnit.SECONDS);//阻塞直到计数为0或者超时
System.out.println("超时结束第一个阻塞,计数:" + countDownLatch.getCount());
countDownLatch.await();//阻塞直到计数为0
System.out.println("结束第二个阻塞,计数:" + countDownLatch.getCount());
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("wait thread finished");
}).start();
}
public static void threadRun(final int i) {
new Thread(() -> {
System.out.println("run thread " + i);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("thread " + i + " 计数减1");
countDownLatch.countDown();//计数减1
}).start();
}
}
结果: