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?
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);
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With