java如何等待线程池种的指定线程结束,才执行主线程
时间: 2024-02-20 16:35:14 浏览: 76
Java中可以使用CountDownLatch(倒计时门闩)来实现等待指定数量的线程执行完毕后再执行主线程。
具体实现步骤如下:
1. 创建一个CountDownLatch对象,其参数为需要等待的线程数量。
2. 在需要等待的线程的run()方法中,执行完任务后调用CountDownLatch的countDown()方法,表示该线程已完成任务。
3. 在主线程中调用CountDownLatch的await()方法,使主线程等待所有线程完成任务后再继续执行。
示例代码如下:
```
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class WaitThreadPool {
public static void main(String[] args) throws InterruptedException {
int threadCount = 5; //线程数量
CountDownLatch latch = new CountDownLatch(threadCount);
ExecutorService executorService = Executors.newFixedThreadPool(threadCount);
for(int i=0; i<threadCount; i++) {
executorService.execute(new Task(latch));
}
latch.await(); //等待所有线程执行完成
System.out.println("所有线程执行完成,主线程继续执行");
executorService.shutdown(); //关闭线程池
}
static class Task implements Runnable {
private CountDownLatch latch;
public Task(CountDownLatch latch) {
this.latch = latch;
}
@Override
public void run() {
try {
//模拟线程执行任务
Thread.sleep((long)(Math.random()*1000));
System.out.println(Thread.currentThread().getName() + " 执行完成");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
latch.countDown(); //任务执行完成,计数器减1
}
}
}
}
```
在该示例中,创建了一个线程池并启动了5个线程执行任务。每个线程执行完任务后调用CountDownLatch的countDown()方法,最终主线程调用CountDownLatch的await()方法等待所有线程执行完任务后再继续执行。
阅读全文
相关推荐
















