写一个countdownlatch demo
时间: 2023-09-01 17:11:03 浏览: 40
下面是一个简单的countdownlatch demo,用于控制多个线程的同步:
```java
import java.util.concurrent.CountDownLatch;
public class CountdownLatchDemo {
public static void main(String[] args) throws InterruptedException {
int threadNum = 5;
CountDownLatch countDownLatch = new CountDownLatch(threadNum);
for (int i = 0; i < threadNum; i++) {
new Thread(new Task(countDownLatch)).start();
}
// 等待所有线程执行完毕
countDownLatch.await();
System.out.println("All threads have finished executing.");
}
static class Task implements Runnable {
private CountDownLatch countDownLatch;
public Task(CountDownLatch countDownLatch) {
this.countDownLatch = countDownLatch;
}
@Override
public void run() {
try {
System.out.println(Thread.currentThread().getName() + " is executing.");
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName() + " has finished executing.");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
countDownLatch.countDown();
}
}
}
}
```
在这个demo中,我们创建了5个线程,并且使用CountDownLatch来控制这些线程的同步。每个线程都会执行一个简单的任务,在任务执行完毕之后调用countDownLatch的countDown方法,表示线程已经执行完毕。主线程调用await方法,等待所有线程执行完毕,然后输出"All threads have finished executing."。