在 EDT 之外执行长时间运行操作的正确方法是什么?
在桌面 Java 1.5 应用程序中(它必须在许多 MacOS X 机器上运行,由于 Apple 的政策,这些机器不会看到 1.6 虚拟机)在 EDT 之外执行冗长计算的正确方法是什么?
例如,当用户单击启动操作的按钮时:我在 EDT 上收到通知,并且想要运行某些方法(例如 crunchData()
)。
这是一种方法:
final Thread t = new Thread( new Runnable() {
public void run() {
crunchData();
}
} );
t.start;
我的意思是:这就是我想要的,但是每次用户启动一个可能长时间运行的任务时,我都会使用上面的习惯用法。而且我觉得我总是不必要地创建大量任务(此外,尽管有时操作可能很长,有时却不会,在这种情况下,我希望应用程序尽可能负责)。
另一种方法是让另一个(非 EDT)线程(或线程池)始终运行,例如在阻塞队列上等待并执行,例如我将排队的 Runnable无论我需要执行长时间的操作。
处理这个问题的正确方法是什么?
编辑:处理如此简单的安装SwingWorker
的正确方法是吗?在 SwingWorker
出现之前,人们是如何处理这个问题的(这看起来很基本)?
In a desktop Java 1.5 application (it has to run on a lot of MacOS X machines that will nerver see a 1.6 VM due to Apple politics) what is a correct way to perform a lengthy computation outside the EDT?
Say, for example, when the user clicks on a button that starts an operation: I get the notification on the EDT and I want to run some method (say crunchData()
).
Here's one way to do it:
final Thread t = new Thread( new Runnable() {
public void run() {
crunchData();
}
} );
t.start;
I mean: this does what I want but every single time the user starts a potentially long running task I use the above idiom. And I feel like I'm always unnecessarily creating lots of task (moreover although sometimes the operation can be lengthy, sometimes it won't and in these case I'd like the app as responsible as possible).
Another way to do it would be to have another (non-EDT) thread (or a pool of threads), always running, say waiting on a blocking queue and executing, say, Runnable that I would enqueue wherever I need to perform a lengthy operation.
What is the correct way to deal with this?
EDIT: Is the correct way to deal with something that simple to install SwingWorker
? How did people deal with this (which seems pretty basic) before SwingWorker
came?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
推荐的方法是让您的 EDT 代码启动 SwingWorker ,它将在外部完成工作并将结果返回给您。
The recommended way is to have your EDT code start a SwingWorker, which will do the job outside and return the result to you.