获得未来进展的能力“目的 [英] ability to get the progress on a Future<T> object

查看:160
本文介绍了获得未来进展的能力“目的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

参考java.util.concurrent包和Future接口,我注意到(除非我错了)开始一个冗长的任务,并能够查询进度的能力只有SwingWorker实现类。 / p>

这提出了以下问题:



有一种方法,在非GUI,非Swing应用程序(成像控制台应用程序)在后台启动一个冗长的任务,并允许其他线程检查进度?在我看来,没有理由为什么这个功能应该限于swing / GUI应用程序。否则,唯一可用的选项,我看到它的方式是通过ExecutorService :: submit返回一个Future对象。但是,Future接口不允许监视进度。

解决方案

显然,Future对象只适用于阻塞和然后接收结果。



您提交的Runnable或Callable对象必须知道如何提供此进度(完成百分比,尝试次数,状态(枚举? )等),并将其作为对对象本身的API调用,或者张贴在某些查找资源(如果需要,在内存映射或数据库中)。为了简单起见,我倾向于喜欢对象本身,特别是因为你很可能需要一个句柄(id)来查找对象或引用对象本身。



这意味着你有3个线程操作。 1表示实际工作,1表示在等待结果时被阻塞,1表示监视线程。最后一个可以根据您的要求共享。


With reference to the java.util.concurrent package and the Future interface I notice (unless I am mistaken) that the ability to start a lengthy tasks and be able to query on the progress only comes with the SwingWorker implementing class.

This begs the following question:

Is there a way, in a non-GUI, non-Swing application (imaging a console application) to start a lengthy task in the background and allow the other threads to inspect the progress ? It seems to me that there is no reason why this capability should be limited to swing / GUI applications. Otherwise, the only available option, the way I see it, is to go through ExecutorService::submit which returns a Future object. However, the base Future interface does not allow monitoring the progress.

解决方案

Obviously, the Future object would only be good for blocking and then receiving the result.

The Runnable or Callable object that you submit would either have to know how to provide this progress (percentage complete, count of attempts, status (enum?) etc) and provide that as an API call to the object itself, or posted in some lookup resource (in memory map or database if necessary). For simplicity I tend to like the object itself, especially since you're going to most likely need a handle (id) to lookup the object or a reference to the object itself.

This does mean that you have 3 threads operating. 1 for the actual work, 1 that is blocked while waiting for the result, and 1 that is a monitoring thread. The last one could be shared depending on your requirements.

这篇关于获得未来进展的能力“目的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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