java swing worker thread to wait for EDT

我是研究僧i 提交于 2019-12-10 05:24:28

问题


I've got a worker thread that should wait for EDT to update the GUI before continuing execution. I've used the publish method to tell EDT to change something. How can i make the worker wait for that change to take place?


回答1:


If it is also your same worker thread that is initiating the GUI changes, then there's a ready-built mechanism for waiting for those changes to be made:

SwingUtilities.invokeAndWait()

should fit the bill nicely.

Another alternative would be to use SwingUtilities.invokeLater() to give the EDT some code to run which will wake your thread up once the EDT becomes idle, i.e. when it gets around to running this task. This would involve firing off invokeLater() immediately followed by a wait() and hoping that the wake-up from the EDI doesn't happen before you do the wait(). This isn't quite foolproof with respect to timing, though.




回答2:


I'm assuming you are using SwingWorker to publish your results. You can use a boolean flag to indicate that the value has been processed. This flag is cleared before publishing intermediate results, and then used to block the thread until it is set. The UI thread sets the flag when it as completed processing the published data.

class MyWorker extends SwingWorker<K,V>
{
    boolean processed = true;

    protected void doInBackground() {
        for (;;) {
            setProcessed(false);
            publish(results);
            waitProcessed(true);
        }
    }

    synchronized void waitProcessed(boolean b) {
        while (processed!=b) {
           wait();
        }
        // catch interrupted exception etc.
    }

    synchronized void setProcessed(boolean b) {
        processed = b;
        notifyAll();
    }


    protected void process(List<V> results) {
       doStuff();
       setProcessed(true);
    }
}


来源:https://stackoverflow.com/questions/3173010/java-swing-worker-thread-to-wait-for-edt

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