【发布时间】:2015-09-29 10:21:48
【问题描述】:
我正在实现Future<Collection<Integer>> 接口,以便在应用程序中的所有线程之间共享一些批量计算的结果。
事实上,我打算将实现Future<Collection<Integer>> 的类的实例放入ApplicationScope 对象中,以便任何其他需要结果的线程只需从object 请求Future 并调用方法@ 987654326@ 就可以了,因此使用了另一个线程执行的计算。
我的问题是关于实现cancel 方法。现在,我会写这样的东西:
public class CustomerFutureImpl implements Future<Collection<Integer>>{
private Thread computationThread;
private boolean started;
private boolean cancelled;
private Collection<Integer> computationResult;
private boolean cancel(boolean mayInterruptIfRunning){
if( computationResult != null )
return false;
if( !started ){
cancelled = true;
return true;
} else {
if(mayInterruptIfRunning)
computationThread.interrupt();
}
}
//The rest of the methods
}
但是方法实现不满足Future的文档,因为我们需要在任何等待结果的线程中抛出CancellationException(已调用get()方法)。
我应该添加另一个像private Collection<Thread> waitingForTheResultThreads; 这样的字段,然后从Collection 中断每个线程,捕获中断的异常,然后throw new CancellationException()?
问题是这样的解决方案对我来说似乎有点奇怪……我不确定。
【问题讨论】:
标签: java multithreading future