Welcome to JiKe DevOps Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
522 views
in Technique[技术] by (71.8m points)

方法中创建的线程池后,执行shutdown后任务还未放入到线程池中,会提前把线程池关闭吗?

比方说下面这个demo

这个方法在创建线程池threadPoolExecutor后,通过for循环向线程池加入任务的过程中,shutdown()方法是不是会先执行,导致任务无法全部加入到线程池中就把线程池关闭了

public String demo(List<File> file,String path) {
    ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(5, 10, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<>());
    for (int x = 0; x < file.size(); x++) {
        final int temp = x;
        threadPoolExecutor.execute(() -> {
            logger.info("threadName:" + Thread.currentThread().getName());
            //添加任务temp
        });
    }
    threadPoolExecutor.shutdown();
    logger.info("执行shutdown():线程池关闭");
    while (true) {
        if (threadPoolExecutor.isTerminated()) {
            logger.info("线程池所有的子线程全部执行完毕!");
            return path;
        }
    }

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

Please log in or register to answer this question.

1 Answer

0 votes
by (71.8m points)
    for (int x = 0; x < file.size(); x++) {
        final int temp = x;
        threadPoolExecutor.execute(() -> {
            logger.info("threadName:" + Thread.currentThread().getName());
            //添加任务temp
        });
    }
    
    threadPoolExecutor.shutdown();

这两部分是同步的啊,怎么会出现你说的那种情况?
当然如果在 shutdown() 之后执行添加任务,会失败的。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to JiKe DevOps Community for programmer and developer-Open, Learning and Share

755k questions

754k answers

5 comments

53.3k users

...