具有可运行性和结果的FutureTask [英] FutureTask with Runnable and Results

查看:123
本文介绍了具有可运行性和结果的FutureTask的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对此进行了谷歌搜索,但仍然无法获得扎实的理解.我找不到使用FutureTask(Runnable runnable, V result)构造函数

I googled on this , but still could not get a solid understanding. I could not find any particular example that uses FutureTask(Runnable runnable, V result) constructor

Java文档说

将来提交(可运行任务, T结果)

Future submit(Runnable task, T result)

提交一个Runnable任务以执行并返回一个Future 代表那个任务. Future的get方法将返回给定的 成功完成后的结果.

Submits a Runnable task for execution and returns a Future representing that task. The Future's get method will return the given result upon successful completion.

根据我的理解,这是在任务完成后futureTask.get(),它将把返回的 结果对象发送给我们,该结果对象与"Runnable"无关"工作.这是可运行"作业已完成的信号.

Looking at this my understanding is upon task completion futureTask.get() it will send us back the given result object passed which has nothing to do with the "Runnable" job. This is kind of a signal that the "Runnable "job is completed.

任何具体用例或任何现实生活中的示例都将真正有帮助

Any concrete usecase or any real life example would be really helpful

还与Enno的答案相结合,它与可能在循环中使用isdone()有何不同.
已编辑 还有为什么不等通知呢?

Also in conjunction to Enno's answer how it is different from using isdone() possibly in a loop.
Edited Also why not wait notify?

推荐答案

因此,它可能来自现实生活中的用例,尽管它可能不代表标准用法.基本上,我正在修改返回了runnable的现有代码.

So, this is derived from a real-life use case, although it might not be representative of standard usage. Basically, I was adapting existing code that returned runnable.

LocalService manager = ...; // this is not thread safe
CompletionService exec = new ExecutorCompletionService( ... );
List<URL> work = ...;
for( URL url : work ) {
   // this is existing code returning Runnable
   Runnable task = createTaskFor(url);
   exec.submit(task, url);
}
// we will report the URLs in the order they complete
for( int i = 0; i < work.size(); i++) {
   URL completed = exec.take();
   // manager isn't thread safe, so all calls to it are on this thread
   manager.reportCompleted(completed);
} 

所以你去了.我只用了一次.结合CompletionService很有用,因为它可以使任务生产和任务完成分离,但仍可以通信.

So there you go. I only used it that one time. It was useful in combination with the CompletionService, since that allows task production and task completion to be decoupled but still communcate.

这篇关于具有可运行性和结果的FutureTask的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆