java swing worker thread to wait for EDT

本小妞迷上赌 提交于 2019-12-05 08:23:41

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.

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