FixedThreadPool的未来等待将在所有线程完成之前返回



在使用Future执行另一个任务之前,我试图等待所有线程完成,但出现了问题,因为我的Future只是等待for循环的最后一个线程。

我的执行器方法:

public static Future<?> downloadImages(Executor e, MainViewController controller, String filePath, String dns, int port, int numImg,
            String offlineUuid, Map<String, String> cookies, String type, String outputFolder) throws SystemException, IOException, InterruptedException {
        String urlImages;
        String filePath2;
        Future future = null;
        if (numImg == 1) {
         //Some Code
        } else {
            type = "multimages";
            ExecutorService es = Executors.newFixedThreadPool(numImg);

            for (int i = 0; i < numImg; i++) {
                filePath2 = "";
                filePath2 = filePath + File.separator + "TargetApp" + File.separator + "TempImage" + i + "Download.zip";
                urlImages = "http://" + dns + ":" + port + Constants.TARGET_SERVICE_DOWNLOADIMAGES_PATH + offlineUuid + "/?pos=" + (i);
                future = es.submit(new DownloaderAndUnzipTask(controller, urlImages, filePath2, outputFolder, cookies, type));
            }
            return future;
        }
        return null;
    }

我的等待方式:

Future future = fullDownloadSelected(tableViewFull.getSelectionModel().getSelectedIndex());
                        if (future != null) {
                            try {
                                future.get();
                                if (future.isDone());
                                System.out.println("Processamento de Imagens Acabou");
                            } catch (ExecutionException ex) {
                                Logger.getLogger(MainViewController.class.getName()).log(Level.SEVERE, null, ex);
                            }

当第一个方法中创建的最后一个线程完成时,会显示我的消息,但当池中的所有线程都完成时,它应该已经完成了。我认为我在for循环中提交执行器的地方出了问题,但我该如何修复它?

您需要捕获返回的每个Future,然后等待每个Future完成(使用get on each)

或者,你可以做一些类似的事情:

ExecutorService es = Executors.newFixedThreadPool(numImg);
List<Callable> tasks = ...
for (int i = 0; i < numImg; i++) {
  tasks.add(your tasks);
}
List<Future<Object>> futures = es.invokeAll(tasks);

其将仅在其中的所有任务完成后返回。

您在每次迭代中重新分配未来
您可以使用invokeAll,它在完成所有提交的任务时返回。

您只是在等待最后一个Future完成。

   future = es.submit(...);
   ...
return future;
...
// in waiting method, wait for the last job to finish
future.get();

这只会等待提交给executor服务的最后一个作业完成——其他作业仍然可以运行。您应该改为从downloadImages()返回ExecutorService。然后在您的等待方法中,您可以:

// you must always shut the service down, no more jobs can be submitted
es.shutdown();
// waits for the service to complete forever
es.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);

在调用方法中创建ExecutorService并将其传递到downloadImages()中可能更有意义。

最新更新