Java 5 SwingWorker 替换
我们的 Swing 应用程序使用优秀的 SwingWorker 类在后台线程中执行一些长时间运行的任务。然而,许多较旧的 Mac 只支持 Java 5,因此我们希望将应用程序编译为 5 而不是 6。由于 SwingWorker 是在 Java 6 中引入的,因此我们无法再使用它。
如果我只需要在后台执行某些操作,然后在完成后在 GUI 中进行通信,那么以下内容是否可以接受?或者我忘记了一些重要的事情?
public static void wannabeSwingWorker(final Runnable doInBackground, final Runnable callback) {
Thread backgroundThread = new Thread(new Runnable() {
public void run() {
doInBackground.run();
SwingUtilities.invokeLater(callback);
}
});
backgroundThread.start();
}
Our Swing application performs some long-running tasks in a background thread using the excellent SwingWorker class. However, a lot of older Macs only support Java 5, so we want to compile our application as 5 instead of 6. Because SwingWorker was introduced in Java 6 we can no longer use it.
Would the following be an acceptable replacement if I only need to do something in the background and then communicate it in the GUI when done? Or am I forgetting something crucial?
public static void wannabeSwingWorker(final Runnable doInBackground, final Runnable callback) {
Thread backgroundThread = new Thread(new Runnable() {
public void run() {
doInBackground.run();
SwingUtilities.invokeLater(callback);
}
});
backgroundThread.start();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我会让其他人评论您的代码的适用性,但作为替代方案,您可以下载 Swingworker 的向后移植以在 Java 5 中使用 此处。
I'll let someone else comment on the suitability of your code, but as an alternative you can download a backport of Swingworker for use in Java 5 here.
您的代码应该可以正常工作;当然,您将失去 SwingWorker 的所有其他功能(返回部分结果和进度、可取消、支持侦听器),
Your code should work correctly; of course you'll lose all the other features of SwingWorker (returning partial results and progress, being cancellable, supporting listeners),
看一下 Foxtrot,它的工作方式与大多数 Swing 并发库不同。
它不是激发后台线程来执行长时间运行的任务,而是通过在 Swing EDT 上执行长时间运行的任务并激发新线程来处理 GUI 事件来模拟 Swing 在显示模式对话框时所采用的方法。
当处理一个长时间运行的任务并返回一个您立即需要执行操作的值时,这会产生一段非常漂亮的、过程性/非并发的程序代码(就像检查 JOptionPane.showConfirmDialog 的返回值一样) (...))。
Take a look at Foxtrot, which works differently than most Swing concurrency libs.
Instead of firing a background thread to execute a long-running task, it emulates the approach taken by Swing when you show a modal dialog box by executing the long running task on the Swing EDT and firing up a new thread to handle GUI events.
When working with a long running task that returns a value that you immediately need to act on, this results in a very nice, procedural/non-concurrent looking piece of program code (exactly like checking the return value from
JOptionPane.showConfirmDialog(...)
).如果您的产品中的 LGPL 代码没有任何问题,则可以使用 SwingWorker 到 Java 5 的向后移植版本。
http://java.net/projects/swingworker
If you don't have any issues with LGPL code in your product, you can use the backport version of SwingWorker to Java 5.
http://java.net/projects/swingworker