CountDownLatch是一个Java的并发工具类,用于使一个线程等待其他线程完成各自的工作。其主要用法如下:
-
创建一个CountDownLatch实例,指定初始计数器的值。
CountDownLatch countDownLatch = new CountDownLatch(3); |
-
在需要等待的线程中调用await()方法,该方法会阻塞当前线程,直到计数器减到0。
countDownLatch.await(); |
-
在其他线程中,每次完成一项工作后,调用countDown()方法来减少计数器的值。
countDownLatch.countDown(); |
当所有线程都完成了各自的工作后,计数器减为0,此时等待的线程会从await()方法返回,继续执行后续代码。
以下是一个简单的示例代码:
java复制代码public class CountDownLatchExample { | |
public static void main(String[] args) throws InterruptedException { | |
CountDownLatch countDownLatch = new CountDownLatch(3); | |
Thread thread1 = new Thread(() -> { | |
System.out.println("Thread 1 started"); | |
try { | |
Thread.sleep(1000); | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
System.out.println("Thread 1 finished"); | |
countDownLatch.countDown(); | |
}); | |
Thread thread2 = new Thread(() -> { | |
System.out.println("Thread 2 started"); | |
try { | |
Thread.sleep(2000); | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
System.out.println("Thread 2 finished"); | |
countDownLatch.countDown(); | |
}); | |
Thread thread3 = new Thread(() -> { | |
System.out.println("Thread 3 started"); | |
try { | |
Thread.sleep(3000); | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
System.out.println("Thread 3 finished"); | |
countDownLatch.countDown(); | |
}); | |
thread1.start(); | |
thread2.start(); | |
thread3.start(); | |
countDownLatch.await(); // 等待所有线程完成工作后返回继续执行后续代码... | |
} | |
} |