使用threadpool执行任务时RejectedExecutionException:JAVA

时间:2016-12-13 05:44:09

标签: java threadpool threadpoolexecutor

Threadpool在提交时拒绝任务。线程池大小是固定的,它是8.虽然我不是将任务总和超过8,但它拒绝。我尝试使用阻塞队列,但它没有帮助我。

这是我的代码段

try {
            List<Future> tasks = new ArrayList<Future>();
            ThreadPoolExecutor tpe = (ThreadPoolExecutor) Executors.newFixedThreadPool(10);
            Process process = new Process();
            ProcessingJobMeta meta = process.getPJM();
            List<CuratedInput> cil = meta.getCuratedInputList();
            for (final CuratedInput ci : cil) {
                for (final Preperation prep : Preperation.values()) {
                    for (final Export export : Export.values()) {
                        Runnable runnable = new Runnable() {
                            public void run() {
                                LOGGER.info("Executing.................." + prep.toString() );
                                LOGGER.info("Executing.................." + export.toString());
                                PreperationFactory.getPreperation(prep.toString(), ci);
                                ExportFactory.getExport(export.toString(), ci);
                            }
                        };
//                      tpe.submit(runnable);
                        tasks.add((Future) tpe.submit(runnable));

                        for (Future p : tasks) {
                            LOGGER.info("---------------inside the futures for loop------------");
                            LOGGER.info("Result of the future executed ------> " + p.get());
                        }

                        tpe.shutdown();

                        while (!tpe.isShutdown()) {

                        }
                    }
                }

            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

1 个答案:

答案 0 :(得分:1)

您的问题是您在循环中关闭池并且注意向已关闭的池添加更多线程。将这些行放在循环之外

tpe.shutdown();

while (!tpe.isShutdown()) {

}

类似这样的事情

List<Future> tasks = new ArrayList<Future>();
        ThreadPoolExecutor tpe = (ThreadPoolExecutor) Executors.newFixedThreadPool(10);
        Process process = new Process();
        ProcessingJobMeta meta = process.getPJM();
        List<CuratedInput> cil = meta.getCuratedInputList();
        for (final CuratedInput ci : cil) {
            .....
        }

        tpe.shutdown();
        while (!tpe.isShutdown()) {

        }

请尝试