如何处理拒绝,以便Future.get()不会永远?

时间:2015-08-01 10:51:54

标签: java multithreading concurrency

我参加了Java的public class MyReject { public static void main(String[] args) { ThreadPoolExecutor executor = new ThreadPoolExecutor(5, 5, 50000L, TimeUnit.MICROSECONDS, new LinkedBlockingQueue<Runnable>(5)); executor.setRejectedExecutionHandler((r, ex) -> { System.out.println("Rejected!"); } ); Task[] tasks = new Task[20]; Future<?>[] future = new Future[20]; for (int i = 0; i < 20; i++) { tasks[i] = new Task(40, "Task " + i); future[i] = executor.submit(tasks[i]); } for (int i = 0; i < 20; i++) { try { System.out.println(future[i].get()); } catch (InterruptedException e) { } catch (ExecutionException e) { } } executor.shutdown(); } 课程。这是我的代码

future[i].get()

}

我发现有些executor将永远等待,因为future[i].get()会提前拒绝相应的任务。我怎么能告诉future[i].get(timeout, TimeUnit)任务被拒绝了,所以你不想再等了?

非常感谢, 附:假设我不想使用{{1}}

2 个答案:

答案 0 :(得分:0)

如果删除对SomeType currentValue, maximumValue; //Encapsulate currentValue and maximumValue void setValue(SomeType value){ currentValue = value; //update the maximum if(value.compareTo(maximumValue) > 0) maximumValue = value; } SomeType getMaximum(){ return maximumValue; } SomeType getCurrent(){ return currentValue; } 的调用,则setRejectedExecutionHandler会在执行者拒绝任务时抛出submit

答案 1 :(得分:0)

您可以在public function get()中取消该任务,在这种情况下,当您尝试在被拒绝的未来调用public function get() { $this->user_model->get(); } 时,它会抛出RejectedExecutionHandler

CancellationException

如果您不想捕获Exception,则可以在Task类中创建自定义属性get,并将其设置在executor.setRejectedExecutionHandler((r, ex) -> { if (r instanceof FutureTask) { ((FutureTask) r).cancel(false); } System.out.println("Rejected!"); });中。在调用Future.get()之前,请检查rejected属性值。