从 SwingWorker 执行 SwingWorker - 等待第一个停止
我试图从另一个 SwingWorker (MainWorker) 执行 SwingWorker (SubWorker),然后我希望 MainWorker 等待 SubWorker 完成。同时,MainWorker 应该根据 SubWorker 的属性变化进行自我更新。
public class MainWorker extends SwingWorker<Void,Void>
{
public Void doInBackground()
{
SubWorker sw = new SubWorker();
sw.execute();
try {
network.get(); // wait for completion
} catch (Exception ex) {
}
return null;
}
}
问题在于,直到 MainWorker 完成后才会调用 SubWorker 的 doInBackground 方法,而 MainWorker 正在等待 SubWorker 完成。
如何让 SubWorker 与 MainWorker 的活动并行运行?
I'm trying to execute a SwingWorker (SubWorker) from another SwingWorker (MainWorker), and then I want the MainWorker to wait for the SubWorker to complete. In the mean time, the MainWorker should update itself according to property changes of the SubWorker.
public class MainWorker extends SwingWorker<Void,Void>
{
public Void doInBackground()
{
SubWorker sw = new SubWorker();
sw.execute();
try {
network.get(); // wait for completion
} catch (Exception ex) {
}
return null;
}
}
The problem is that the SubWorker's doInBackground method is not called until the MainWorker has finished, while the MainWorker is waiting for the SubWorker to finish.
How can I let the SubWorker run parallel to the MainWorker's activities?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果你只有一个子工作人员,我不确定有什么意义 - 为什么你不能只在 SW 主体中执行任务?
如果您有多个并行子任务,并且想要对它们进行分组并报告其进度,那么您实际上并不需要单独的 SwingWorkers - 只需启动线程或使用执行器来安排任务。如果要发布临时结果,请将阻塞队列传递给任务,任务将在其中推送更新。
主要(或者更确切地说是唯一)SwingWorker 将从该队列中获取项目并使用publish()/process() 方法更新GUI。当子任务完成工作时,它可以将特殊令牌推送到队列中(或为空)。这样您就可以跟踪未完成的子任务并决定何时终止循环。
或者,如果您有一堆独立的任务,您可以使用 CompletionService 并以类似的方式从软件更新状态。
If you have only one sub-worker, I'm not sure what is the point - why can't you just execute the task in the SW body?
If you have multiple parallel sub-tasks, and you want to group them and report on their progress, you don't really need separate SwingWorkers - just start threads or use an executor to schedule the tasks. If you want to publish interim results, pass a blocking queue to the tasks, where they would push the updates.
The main (or rather the only) SwingWorker would take items from that queue and update the GUI using the publish()/process() methods. When a subtask finishes work, it can push special token in the queue (or null). That's how you can keep track of the outstanding subtasks and decide when to terminate the loop.
Alternatively, if you have a bunch of self-contained tasks you can use CompletionService and update the status in similar way from the SW.