I have a worker thread that creates a runnable object and calls runOnUiThread on it, because it deals with Views and controls. I'd like to use the result of the work of the runnable object right away. How do I wait for it to finish? It doesn't bother me if it's blocking.
Create an Object called lock . Then after runOnUiThread(myRunnable); , you can call lock. wait() .
Just scratching out the highlights
synchronized( myRunnable ) { activity.runOnUiThread(myRunnable) ; myRunnable.wait() ; // unlocks myRunable while waiting }
Meanwhile... in myRunnable...
void run() { // do stuff synchronized(this) { this.notify(); } }
Perhaps a little simplistic but a mutex will do the job:
final Semaphore mutex = new Semaphore(0); activity.runOnUiThread(new Runnable() { @Override public void run() { // YOUR CODE HERE mutex.release(); } }); try { mutex.acquire(); } catch (InterruptedException e) { e.printStackTrace(); }
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