要实现该需求可借助线程池的awaitTermination和isTerminated方法来实现,也可使用CountDownLatch计数器来实现。
1.使用awaitTermination方法阻塞主线程, 直至线程池关闭
public static void main(String[] args) throws InterruptedException {
ExecutorService threadPool= Executors.newFixedThreadPool(10);
threadPool.submit(() -> {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("休息5秒-----------------------------");
});
threadPool.submit(() -> {
try {
Thread.sleep(15000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("休息15秒-----------------------------");
});
threadPool.submit(() -> {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("休息10秒-----------------------------");
});
threadPool.shutdown();
threadPool.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
System.out.println("执行结束!");
}
运行结果
2.使用isTerminated方法,当调用shutdown()后,线程提交任务完成时变为true
public static void main(String[] args) {
ExecutorService threadPool= Executors.newFixedThreadPool(10);
threadPool.submit(() -> {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("休息5秒-----------------------------");
});
threadPool.submit(() -> {
try {
Thread.sleep(15000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("休息15秒-----------------------------");
});
threadPool.submit(() -> {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("休息10秒-----------------------------");
});
threadPool.shutdown();
while (!threadPool.isTerminated()){
if (threadPool.isTerminated()) break;
}
System.out.println("执行结束!");
}
运行结果
3.使用CountDownLatch该方法不依赖于线程池,但是需知道有多少个线程,通过countDown方法减少对应线程计数实现。
public static void main(String[] args) throws InterruptedException {
CountDownLatch count = new CountDownLatch(3);
ExecutorService threadPool= Executors.newFixedThreadPool(10);
threadPool.submit(() -> {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("休息5秒-----------------------------");
count.countDown();
});
threadPool.submit(() -> {
try {
Thread.sleep(15000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("休息15秒-----------------------------");
count.countDown();
});
threadPool.submit(() -> {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("休息10秒-----------------------------");
count.countDown();
});
threadPool.shutdown();
count.await();
System.out.println("执行结束!");
}
运行结果