於是我問了一個問題前陣子:Over here說問這個問題:「我怎樣才能使他們是否花費太長時間我的線程會被殺掉」爲什麼我的線程在失敗時超時?
我已經實現了那裏,但在某些罕見的情況下提到的解決方案,其中線程超時,程序仍可能失敗/鎖定(請參閱:保持main()方法處於打開狀態,並阻止程序的進一步cron運行)。
下面是我使用的源:
//Iterate through the array to submit them into individual running threads.
ExecutorService threadPool = Executors.newFixedThreadPool(12);
List<Future<?>> taskList = new ArrayList<Future<?>>();
for (int i = 0; i < objectArray.length; i++) {
Future<?> task = threadPool.submit(new ThreadHandler(objectArray[i], i));
taskList.add(task);
Thread.sleep(500);
}
//Event handler to kill any threads that are running for more than 30 seconds (most threads should only need .25 - 1 second to complete.
for(Future future : taskList){
try{
future.get(30, TimeUnit.SECONDS);
}catch(CancellationException cx){ System.err.println("Cancellation Exception: "); cx.printStackTrace();
}catch(ExecutionException ex){ System.err.println("Execution Exception: ");ex.printStackTrace();
}catch(InterruptedException ix){ System.err.println("Interrupted Exception: ");ix.printStackTrace();
}catch(TimeoutException ex) {future.cancel(true);}
}
threadPool.shutdown();
threadPool.awaitTermination(60, TimeUnit.SECONDS);
所以我的問題是:這個代碼實現,爲什麼是執行服務爲30秒不切東西了。
注意:每個任務的超時時間都會增加。例如如果第一項任務需要29秒,則第二項任務需要59秒才能完成。 –
你可以評論如何解決這個問題嗎?因爲這不是意圖。 –
我添加了一個答案/解決超時時間較長的原因之一。 –