目录
CountDownLatch简介
CountDownLatch是一个同步工具类。个人理解这就是一个计数器,它有一个预设值,当其值减为零的时候,当前线程就可以执行了。
CountDownLatch的用法
CountDownLatch中的方法不多,其中有三个经常用到的方法,await(),await(long, TimeUnit)和countDown()。
- countDown():该方法是对预设值进行减一对操作;
- await():使当前线程等待,直到预设值为零;
- await(long, TimeUnit):使当前线程等待一定时间,直到预设值为零或超时。
代码示例
public class test implements Runnable{
public static void main(String[] args) {
for (int i = 0; i < 5; i++){
new Thread(new test()).start();
}
System.out.println("任务结束");
}
@Override
public void run() {
System.out.println("线程" + Thread.currentThread().getId() + "开始");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("线程" + Thread.currentThread().getId() + "结束");
}
}
运行结果
使用CountDownLatch
class test2 implements Runnable{
public static final CountDownLatch count = new CountDownLatch(5);
public static void main(String[] args) {
for (int i = 0; i < 5; i++){
new Thread(new test2()).start();
}
try {
count.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("任务结束");
}
@Override
public void run() {
System.out.println("线程" + Thread.currentThread().getId() + "开始");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("线程" + Thread.currentThread().getId() + "结束");
count.countDown();
}
}
运行结果
CountDownLatch的使用场景
- 适用于当前线程等待多个其他线程执行完后才可继续运行的情况,
- 例如分批往数据库中导入数据,需要等待导入完成后统计执行时间;