我正在使用java.util.concurrent包创建一个并行程序。我有两条线:
我正在指定线程执行超时-假设线程-1没有在指定的超时内完成执行,那么我必须拦截线程-1,继续执行线程-2并显示线程-2导致jsp (注意:如果两个线程都需要太多时间来处理请求,那么我不希望UI等到它们完成)。
我尝试了下面的代码,但它抛出了一个InterruptedException。当一项任务陷入更大的泥潭时,我如何继续执行其他任务呢?
ExecutorService executor = Executors.newFixedThreadPool(2);
CompletionService<ArrayList<AvailableWeatherDetailVO>> compService = new ExecutorCompletionService<ArrayList<AvailableWeatherDetailVO>>(executor);
// Start amazonTask using thread-1
try{
compService.submit(amazonTask).get(20, TimeUnit.MILLISECONDS);
amazonFuture = compService.take();
amazonFinalList =(ArrayList<AvailableWeatherDetailVO>)amazonFuture .get() }
catch (TimeoutException e) {
compService.submit(amazonTask).cancel(true);
//throw new TimeoutException("Thread not executed with in speifed time");
}
// Start googleTask using thread-2
try{
compService.submit(googleTask).get(100, TimeUnit.MILLISECONDS);
googleFuture = compService.take();
googleFinalList =(ArrayList<AvailableWeatherDetailVO>)googleFuture .get() }
catch (TimeoutException e) {
compService.submit(googleTask).cancel(true);
//throw new TimeoutException("Thread not executed with in speifed time");
}发布于 2012-07-08 22:24:43
您的意思是thread2只在thread1失败时才开始执行,这一点尚不清楚。
或者,它们都在执行吗?但是如果thread1完成了,您希望使用它的结果,否则要使用thread2的结果。
在我看来,你应该把线1附加到未来。然后通过超时获得结果(从主线程)。如果Future.get()超时,则从第二个线程获得结果。
不知道我是否明白你的意思。如果这不是你想要的,请澄清。
https://stackoverflow.com/questions/11310452
复制相似问题