所以我编写了一段代码,它将通过任务处理程序提交一组对象,我有一个实例出现在程序崩溃并且没有正确关闭的地方......这段代码会做我认为它应该做的事情吗?
在我看来,以下代码应该获取一个对象,将其传递给处理程序,然后等待最多 30 秒,如果该线程尚未完成,则将其杀死。正确的?
//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();
}
}
threadPool.shutdown(); // SHUT. DOWN. EVERYTHING.