使用 shutdown() + awaitTermination()
public class Test {
public static int threadNum = 10;
public static void main(String[] args) throws InterruptedException {
ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
for (int i = 0; i < threadNum; i++) {
executorService.execute(new Runnable() {
@Override
public void run() {
//do work
}
});
}
executorService.shutdown();
executorService.awaitTermination(1,TimeUnit.HOURS);
}
}
使用CountDownLatch
public class Test {
public static int count = 0;
public static int threadNum = 10;
public static void main(String[] args) throws InterruptedException {
ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
CountDownLatch countDownLatch = new CountDownLatch(threadNum);
for (int i = 0; i < threadNum; i++) {
executorService.execute(new Runnable() {
@Override
public void run() {
//do work
countDownLatch.countDown();
}
});
}
countDownLatch.await();
}
}
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论