countdownlatch用法
时间: 2023-07-08 15:14:49 浏览: 110
CountDownLatch是Java中提供的一个同步工具类,它可以用来控制一个或多个线程等待多个线程的操作完成。
CountDownLatch的用法如下:
1. 创建一个CountDownLatch对象,指定需要等待的线程数。
```
CountDownLatch latch = new CountDownLatch(5);
```
2. 每个需要等待的线程执行完后调用CountDownLatch的countDown方法减少计数器。
```
latch.countDown();
```
3. 等待所有线程执行完毕后,调用CountDownLatch的await方法进行等待。
```
latch.await();
```
4. 在所有线程执行完毕后,主线程或其他线程可以继续执行自己的操作。
示例代码:
```
import java.util.concurrent.CountDownLatch;
public class CountDownLatchDemo {
public static void main(String[] args) throws InterruptedException {
CountDownLatch latch = new CountDownLatch(5);
for (int i = 0; i < 5; i++) {
new Thread(() -> {
System.out.println(Thread.currentThread().getName() + " is working...");
try {
// 模拟线程执行时间
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " done");
latch.countDown();
}).start();
}
System.out.println("Waiting for all threads to finish...");
latch.await();
System.out.println("All threads have finished, continue to execute the main thread.");
}
}
```
运行结果:
```
Waiting for all threads to finish...
Thread-0 is working...
Thread-2 is working...
Thread-1 is working...
Thread-3 is working...
Thread-4 is working...
Thread-1 done
Thread-3 done
Thread-0 done
Thread-2 done
Thread-4 done
All threads have finished, continue to execute the main thread.
```
阅读全文