java多线程使用CountDownLatch
时间: 2023-10-15 16:22:41 浏览: 110
JAVA多线程CountDownLatch使用详解
在 Java 中,CountDownLatch 是一种同步工具,它可以用来控制线程的执行顺序或者等待其他线程完成某些操作。下面是一个使用 CountDownLatch 的示例,用于实现多线程的协调:
```java
import java.util.concurrent.CountDownLatch;
public class MultiThreadExample {
public static void main(String[] args) throws InterruptedException {
int threadCount = 5;
CountDownLatch latch = new CountDownLatch(threadCount);
for (int i = 0; i < threadCount; i++) {
Thread thread = new Thread(new Worker(latch));
thread.start();
}
System.out.println("Main thread is waiting for workers to finish.");
latch.await();
System.out.println("All workers have finished. Main thread can continue.");
}
static class Worker implements Runnable {
private final CountDownLatch latch;
public Worker(CountDownLatch latch) {
this.latch = latch;
}
@Override
public void run() {
try {
System.out.println("Worker is performing some task.");
Thread.sleep(1000);
System.out.println("Worker has finished its task.");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
latch.countDown();
}
}
}
}
```
在上面的示例中,我们创建了一个 CountDownLatch 对象,并将其初始化为预期的线程数量(5)。然后,在主线程中创建了 5 个 Worker 线程,并启动它们。每个 Worker 线程都会执行一些任务,然后调用 `latch.countDown()` 来通知 CountDownLatch 已经完成了一部分工作。最后,主线程调用 `latch.await()` 来等待所有 Worker 线程完成任务。
当所有 Worker 线程完成任务后,主线程就会继续执行。这样,我们就通过 CountDownLatch 来协调多线程的执行顺序了。
阅读全文