使用了executorService.execute后对于线程池中的线程使用join方法不能使线程执行完。


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()并不能让线程运行完毕,线程池就已经关闭了,原因是什么?

  1. 不明白你想表达什么。又是ExecutorService, 又是Thread[],本身ThreadPool就是来帮你管理任务的
  2. execute(Runnable task);接收的是一个Runnable接口,你传入的是Thread,虽然没什么问题。但是你又在调用Thread类里的join()?根本没有意义
  3. shutdown();本身就带有等待线程池中的线程执行完毕的功能如:
    pool.shutdown();
    while (!pool.awaitTermination(5, TimeUnit.SECONDS)) {
     // 5秒没完成
    }
    
  4. 一般可以用CountDownLatch来做线程执行完毕的功能
  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");
    }