What threads are allowed to call SwingWorker#publish?

随声附和 提交于 2019-12-23 20:15:32

问题


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

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.

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?

Thanks, Carsten

[Edit] 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);
  }
}

回答1:


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.

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,

Do you have any reference for your answer, that [other] worker threads are not allowed to use 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.




回答2:


There isn't any limitation on which Threads can call SwingWorker#publish().



来源:https://stackoverflow.com/questions/6516159/what-threads-are-allowed-to-call-swingworkerpublish

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!