awaitTermination()是一个阻塞方法。它必须等线程池退出后才会结束自身。可以设置阻塞时间。
public class Test { public static void main(String[] args) throws IOException, InterruptedException { ExecutorService pool = Executors.newFixedThreadPool(2); for (int i = 0; i < 10; i++) { Runnable run = new Runnable() { @Override public void run() { System.out.println("线程运行" + Thread.currentThread().getName()); } }; service.execute(run); } pool.shutdown(); while (!pool.awaitTermination(1, TimeUnit.SECONDS)) { System.out.println("线程池没有关闭"); } System.out.println("线程池已经关闭"); } }
时间: 2024-10-30 13:54:25