ExecutorService executorService = Executors.newFixedThreadPool(3);
Thread[] threads = new Thread[10];
for (int i = 0; i < 10; i++) {
RunnableThread runnableThread = new RunnableThread(String.valueOf(i));
Thread threadRunnable = new Thread(runnableThread);
threads[i] = threadRunnable;
executorService.execute(threadRunnable);
threads[i].join();
}
executorService.shutdown();
使用 threads[i].join()并不能让线程运行完毕,线程池就已经关闭了,原因是什么?
pool.shutdown();
while (!pool.awaitTermination(5, TimeUnit.SECONDS)) {
// 5秒没完成
}
public static void main(String[] args) throws InterruptedException {
Thread[] threads = new Thread[10];
for (int i = 0; i < 10; i++) {
int finalI = i;
threads[i] = new Thread(() -> {
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(finalI);
});
}
for (Thread thread : threads) {
thread.start();
}
for (Thread thread : threads) {
thread.join();
}
System.out.println("done");
}