哪些线程可以调用 SwingWorker#publish? [英] What threads are allowed to call SwingWorker#publish?

查看:25
本文介绍了哪些线程可以调用 SwingWorker#publish?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

标准场景:用户按下按钮并开始大任务.EventThread 创建 SwingWorker 来执行任务并继续生活.

Standard scenario: User presses button and starts big task. EventThread creates SwingWorker to execute the task and get's on with life.

现在,由于大任务是高度可并行化的,SwingWorker 线程做的第一件事就是创建一堆工作线程并完成工作.

Now, since the big task is highly parallelizable, the first thing the SwingWorker thread does is to create a bunch of worker threads and farms the work out.

我的问题:是否允许工作线程调用 SwingWorker#publish() 来触发 GUI 更新,或者只是 SwingWorker 线程允许这样做吗?

My question: Are the worker threads allowed to call SwingWorker#publish() to trigger a GUI update or is only the SwingWorker thread allowed to do so?

谢谢,卡斯腾

一些伪代码使我的用例更清晰一些.问题基本上是:下面的代码好吗?如果我省略 waitForAllWorkerThreadsT​​oFinish(); 会怎样?

Some pseudo code to make my use-case a bit clearer. The quesiton is basically: Is the code below OK? And what if I leave out waitForAllWorkerThreadsToFinish();?

public class MySwingWorker extends SwingWorker {

  class MyWorkerThread extends Runnable {
    void run() {
      while(!exitCondition) {
        doSomeWork();
        publish(progressUpdate);
        reEvaluateExitCondition();
      }
    }
  }

  public Void doInBackground() {
    createAndStartBunchOfMyWorkerThreads();
    waitForAllWorkerThreadsToFinish();
  }

  void process(List<V> chunks) {
    updateGuiWithProgress(chunks);
  }
}

推荐答案

一般来说,没有;publish() 旨在在后台线程上运行,该线程本身必须同步来自附属工作人员的所有结果.幸运的是,您在设计后台线程如何执行此操作方面有相当大的自由度.例如,这个示例使用CountDownLatch.

In general, no; publish() is intended to run on the background thread, which must itself synchronize all the results coming from the subsidiary workers. Fortunately, you have considerable latitude in designing how the background thread does this. For instance, this example uses CountDownLatch.

附录:waitForAllWorkerThreadsT​​oFinish() 看起来是 CountDownLatch.MyWorkerThread 绝对应该MySwingWorker 以外的线程调用 publish() 而不同步访问任何共享数据.MyWorkerThread 可以使用 invokeLater(),但顺序不可靠.

Addendum: waitForAllWorkerThreadsToFinish() looks like a good use case for CountDownLatch. MyWorkerThread definitely should not call publish() from a thread other than MySwingWorker without synchronizing access to any shared data. MyWorkerThread can update the GUI using invokeLater(), but the order won't be reliable.

附录:你问了一个非常实际的问题,

Addendum: You asked the very practical question,

您的答案是否有任何参考,[其他] 工作线程不允许使用 publish()?

Do you have any reference for your answer, that [other] worker threads are not allowed to use publish()?

内存一致性属性 是一个很好的总结.实际上,您将调用 publish() 来自多个线程,无需同步.结果将是不可预测的.

Memory Consistency Properties is a good summary. In effect, you would be calling publish() from multiple threads without synchronization. The results would be unpredictable.

这篇关于哪些线程可以调用 SwingWorker#publish?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆