当 Callable 返回特定结果时停止 Executor
我想阻止执行器运行更多的 Future 对象,即使它们已提交给执行器。 通过 Executor 运行多个线程都可以正常工作,但是当 Callable 之一返回布尔值 TRUE 时,Executor 应该停止。当前正在运行的 Future 已经完成了,这很好,但继续剩下的就太浪费时间了。
Set<Future<Boolean>> calculationSet = new HashSet<Future<Boolean>>();
threadPool = Executors.newFixedThreadPool(3);
int x = nextX();
int y = nextY();
do {
Callable<Boolean> mathCalculation = new MathCalculation(x, y);
Future<Boolean> futureAttempt = threadPool.submit(mathCalculation);
calculationSet.add(futureAttempt);
x = nextX();
y = nextY();
} while (runSomeMore());
其中 MathCalculation 实现了 Callable 接口,其 call() 方法返回一个布尔值。
在每次迭代中搜索计算集并不是一种选择,因为该集将变得非常大,并且由于多线程情况,它显然无法工作。 有办法实现这一点吗?
I'd like to stop an Executor from running any more Future objects even if they have been submitted to the Executor.
Getting multiple threads running though an Executor all works fine and well but the Executor should stop when one of the Callable's returns a Boolean TRUE. It's fine that the current running Future's complete but it would be a waste of time to continue the rest.
Set<Future<Boolean>> calculationSet = new HashSet<Future<Boolean>>();
threadPool = Executors.newFixedThreadPool(3);
int x = nextX();
int y = nextY();
do {
Callable<Boolean> mathCalculation = new MathCalculation(x, y);
Future<Boolean> futureAttempt = threadPool.submit(mathCalculation);
calculationSet.add(futureAttempt);
x = nextX();
y = nextY();
} while (runSomeMore());
Where MathCalculation implements the Callable interface and its call() method returns a Boolean value.
Searching through the calculationSet on each iteration isn't an option since the set will become quite large and it will obviously not work because of the multi threaded situation.
Is there a way to achieve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您希望可调用对象停止执行程序服务,我建议您创建一个包装器或更改可调用对象来执行此操作。
If you want the callable to stop the executor service, I suggest you create a wrapper or change the Callable to do it.
您还可以使用 ExecutorCompletionService
http:// download.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/ExecutorCompletionService.html
此 JavaDoc 顶部有两个示例,第二个示例表示:
“假设 .. . 您希望使用一组任务的第一个非空结果,忽略遇到异常的任何任务,并在第一个任务准备就绪时取消所有其他任务:”,后面是示例代码。
Thant 听起来很有希望,它能解决您的问题吗?
You could also use ExecutorCompletionService
http://download.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/ExecutorCompletionService.html
There are two examples in top of this JavaDoc and second one says:
"Suppose ... that you would like to use the first non-null result of the set of tasks, ignoring any that encounter exceptions, and cancelling all other tasks when the first one is ready:", followed by sample code.
Thant sounds quite promising, does it solve your problem?