SwingWork 链接
我正在改进 Swing 应用程序的可用性。我正在尝试添加 SwingWorks 来卸载 EDT 中运行的一些 DB 和 IO 调用,从而锁定用户界面。它在很大程度上适用于不依赖于其他任务的独立任务。
我的问题是一些数据库调用相互依赖(任务2必须在任务1之后发生)。例如,假设我有一个任务 1 进行数据库调用并更新组合框,任务 2 进行数据库调用并更新 JList,但任务 2 需要更新组合框。我所拥有的是,Task2 依赖于 Task1 DB 调用 (doInBackground()) 以及对 ComboBox 的更新正在完成 (done())(因此两者都需要完成 doInBackground 和 did)。有没有好的办法解决这个问题呢?有什么好方法可以让 Task2 等待 Task1.doInBackground() 和 Task1.done() 完成。
I am in a process of improving usability of a Swing application. I am trying to add SwingWorks to offload some of the DB and IO calls that were running in the EDT and thus locking up the user interface. It has worked for the most part with isolated tasks that have no dependency from other tasks.
My problem is that some DB calls are dependent on each other (Task2 must happen after Task1). For example say I have a Task1 that makes a DB call and updates a ComboBox and I have Task2 that makes a DB call and updates a JList, but Task2 needs the updates to the ComboBox. What I have is that Task2 dependents on Task1 DB calls (doInBackground()) and the updates to ComboBox being finished (done()) (so both need to be finished doInBackground and done). Is there a good way of solving this? What’s a good way to enable Task2 wait on Task1.doInBackground() and Task1.done() to finish.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以通过多种方式做到这一点。其一将使您能够继续使用 SwingWorker。您可以使用 CountDownLatch。将闩锁传递给任务 1 和任务 2。在任务 2 的 run 方法中,在闩锁上
await
,当任务 1 完成时,在闩锁上调用countDown
。使用它看起来像
替代方案是使用ExecutorService。提交task1,获取其对应的Future,将其分配给task2,并在task1的Future上使用
get()
。You can do this a number of ways. One will enable you to continue to use SwingWorker. You can use a CountDownLatch. Pass the latch to both task 1 and task 2. In task 2's run method
await
on the latch and when task 1 is complete callcountDown
on the latch.And using it would look like
The alternative would be to use
ExecutorService
. Submit task1, get its corresponding Future, assign that to task2 andget()
on task1's future.