SwingWorker同步方法队列阻塞还是什么?

发布于 2024-12-18 12:44:21 字数 601 浏览 2 评论 0原文

理论问题。如果我有两个 SwingWorker 和一个带有方法的 outputObject

public void synchronized outputToPane(String output)

如果每个 SwingWorker 中都有一个循环,如下所示:

//SwingWorker1
while(true) { 
     outputObject.outputToPane("garbage");
}
//SwingWorker2
Integer i=0;
while(true) {
     outputObject.outputToPane(i.toString());
     i++;
}

它们将如何交互? outputToPane 方法是否从一个线程接收参数并阻塞另一个线程,直到第一个线程完成为止,或者它是否构建一个将按照收到的顺序执行的任务队列,或者其他选项?

我问的原因:
我有两个线程将进行一些繁重的数字运算,一个具有不可暂停的数据流,另一个来自文件。我希望他们在达到某些里程碑时都能输出到中央消息传递区域;但是,在等待另一个线程完成输出时,我不能冒数据流被阻塞的风险。那时我将面临丢失数据的风险。

Theoretical question. If I have two SwingWorkers and an outputObject with method

public void synchronized outputToPane(String output)

If each SwingWorker has a loop in it as shown:

//SwingWorker1
while(true) { 
     outputObject.outputToPane("garbage");
}
//SwingWorker2
Integer i=0;
while(true) {
     outputObject.outputToPane(i.toString());
     i++;
}

How would those interact? does the outputToPane method receive an argument from one thread and block the other one until it finishes with the first, or does it build a queue of tasks that will execute in the order received, or some other option?

The reason I ask:
I have two threads that will be doing some heavy number crunching, one with a non-pausable data stream and the other from a file. I would like them both to output to a central messaging area when they hit certain milestones; however, I CANNOT risk the data stream getting blocked while it waits for the other thread to finish with the output. I will risk losing data then.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

说不完的你爱 2024-12-25 12:44:21

synchronized 仅保证互斥。不公平,这实际上意味着您的工作人员可能会很好地交替,或者第一个工作人员可能会获得优先权并完全阻止第二个工作人员直到完成,或者介于两者之间。

有关更多信息,请参阅 Reentrantlock 文档关于公平。也许您可以考虑使用它而不是synchronized。可能更好的选择是使用 Queue

synchronized only guarantees mutual exclusion. Is not fair, which in practice means that your workers might alternate quite nicely, or the first one might get precedence and block the second one completely until finished, or anything between.

See Reentrantlock docs for more about fairness. Maybe you could consider using it instead of synchronized. Probably even better alternative would be using a Queue.

剑心龙吟 2024-12-25 12:44:21

我建议您在消息传递区域中有两个输出对象。因为如果一个线程开始修改输出答案,那么另一个线程将不得不等待它完成。即使您可以对其进行优化以使其足够快,信息的实际显示也会随着时间的推移而使您的线程彼此减慢。

尽管您可能尝试同步它们,但结果可能并不总是 100% 安全

I would advise you to have two output object in your messaging area. Because if one thread starts to modify the output answer then the other one will have to wait for it to finish. Even if you can optimize it to make it fast enough, the actual display of info would make your threads slow each others down over time.

Although you might try to synchronize them, the result might not always be 100% safe

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文