Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java swing worker thread to wait for EDT

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?

like image 894
Mihaela Grigore Avatar asked Jul 03 '10 22:07

Mihaela Grigore


2 Answers

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);
    }
}
like image 102
mdma Avatar answered Nov 15 '22 07:11

mdma


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.

like image 20
Carl Smotricz Avatar answered Nov 15 '22 08:11

Carl Smotricz