Java有内置的“反转”吗?摇摆工人
SwingWorker
允许您在后台Thread
中准备一些数据,然后在 EDT 中使用它。我正在寻找一个执行相反操作的实用程序:在 EDT 中准备数据,然后将其传递给后台线程。
如果您好奇,用例是将 JTable 的状态保存到磁盘(列顺序、大小等)。我需要在 EDT 中与其模型对话,但不想从此线程写入磁盘。
类似于:
void saveCurrentState(final Table table) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
TableColumns state = dumpState(table);
saveToDisk(table.getTableKey(), state);
}
});
}
dumpState()
需要在 EDT 中运行。 saveToDisk()
不应在 EDT 中运行。整个事情被故意包装在 invokeLater()
中,我无法用 invokeAndWait()
替换它。
SwingWorker
lets you prepare some data in a background Thread
and then use it in EDT. I am looking for a utility that does the opposite: Prepare data in EDT, and then pass it to a background Thread
.
If you're curious, the use case is saving state of a JTable
to disk (column order, size, etc.). I need to talk to its model in EDT, but don't want to write to disk from this thread.
Something like:
void saveCurrentState(final Table table) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
TableColumns state = dumpState(table);
saveToDisk(table.getTableKey(), state);
}
});
}
dumpState()
needs to run in EDT. saveToDisk()
should NOT run in EDT. The whole thing is deliberately wrapped in invokeLater()
, and I cannot replace it with invokeAndWait()
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可能正在寻找
ExecutorService< /代码>
。使用
Executors.newCachedThreadPool()
– 或其他newXXX()
方法,但该方法对于大多数用途来说应该没问题。也就是说,我相信这也是您可以使用
SwingWorker
完成的事情。只需在创建SwingWorker
之前在事件处理程序中准备好数据即可 - 您已经在 EDT 中了。如果您需要从非 EDT 线程启动此操作,请使用SwingUtilities.invokeAndWait()
准备数据,然后分离另一个线程来执行写入操作(或在同一个非 EDT 线程中执行此操作) )SwingWorker
和ExecutorService
提供相同的基本服务 - 将一些工作分拆到后台线程中,而无需显式管理其生命周期。SwingWorker
有一种与 EDT 通信的便捷方法,无需在不需要使用的地方使用invokeLater()
,并且ExecutorService
> 支持 futures 作为与异步任务通信的更通用(非 Swing 特定)方式。对于您的一劳永逸用例来说,两者都很好。You're probably looking for
ExecutorService
. Get one usingExecutors.newCachedThreadPool()
– or the othernewXXX()
methods, but that one should be okay for most uses.That said, I believe this is something you can do with
SwingWorker
as well. Just prepare your data in the event handler before you create aSwingWorker
– you're already on the EDT there. If you need to initiate this from a non-EDT thread, prepare the data usingSwingUtilities.invokeAndWait()
, and then spin off another thread to do the writing (or do it in the same non-EDT thread you started with.)SwingWorker
andExecutorService
provide the same basic service – spin off some work into a background thread without having to manage its lifecycle explicitly.SwingWorker
has a convenient method of communicating with the EDT without usinginvokeLater()
all over the place that you don't need to use, andExecutorService
supports futures as a more general (non-Swing-specific) way of communicating with asynchronous task. For a fire-and-forget use case as yours both are fine.