一..一 2021-08-16 14:19 采纳率: 0%
浏览 144
已结题

使用了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条回答 默认 最新

  • zlebhs 2021-08-16 16:24
    关注
    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");
        }
    
    评论

报告相同问题?

问题事件

  • 已结题 (查看结题原因) 8月17日
  • 创建了问题 8月16日

悬赏问题

  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用