[英]Future waiting for FixedThreadPool is returning before all Threads finish
我試圖等待所有線程完成后再使用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,然后等待每個完成(使用get on)
您也可以執行以下操作:
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);
僅在其中所有任務完成后才返回。
您只是在等待最后的Future
完成。
future = es.submit(...);
...
return future;
...
// in waiting method, wait for the last job to finish
future.get();
這僅等待提交給executor-service的最后一個作業完成-其他作業仍可以運行。 您應該改為從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()
可能更有意義。
您將在每次迭代中重新分配未來。
您可以使用invokeAll ,當所有提交的任務完成時返回。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.