import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
/**
* 闭锁
* https://www.cnblogs.com/takumicx/p/9698867.html
*/
public class CountDownLatchTest {
private static CountDownLatch countDownLatch;
public static void main(String[] args) throws InterruptedException {
int count = 10;
// 初始化计数器值为10
countDownLatch = new CountDownLatch(count);
// 开启10个子线程执行子任务
for (int i = 0; i < count; i++) {
Thread thread = new Thread(new CountDownThread(countDownLatch, i));
thread.start();
}
// 主线程等待,直到所有子任务完成
countDownLatch.await();
// 模拟主线程执行后续工作
TimeUnit.SECONDS.sleep(1);
System.out.println("任务执行完毕!");
}
private static class CountDownThread implements Runnable {
CountDownLatch countDownLatch;
// 子任务序号
int taskNum;
public CountDownThread(CountDownLatch countDownLatch, int taskNum) {
this.countDownLatch = countDownLatch;
this.taskNum = taskNum;
}
@Override
public void run() {
try {
// 模拟子任务的执行
TimeUnit.MILLISECONDS.sleep(30);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
// 任务执行完毕,则调用countDown方法使计数器值减少1
countDownLatch.countDown();
}
System.out.println("子任务:" + taskNum + " 执行完毕!");
}
}
}
来源:oschina
链接:https://my.oschina.net/u/3777515/blog/3214940