In my app, I have the following code running on a background thread:
MyRunnable myRunnable = new MyRunnable();
runOnUiThread(myRunnable);
synchronized (myRunnable) {
myRunnable.wait();
}
//rest of my code
And MyRunnable looks like this:
public class MyRunnable implements Runnable {
public void run() {
//do some tasks
synchronized (this) {
this.notify();
}
}
}
I want the background thread to continue after myRunnable has finished executing. I've been told that the above code should take care of that, but there are two things I don't understand:
If the background thread acquires myRunnable's lock, then shouldn't myRunnable block before it's able to call notify() ?
How do I know that notify() isn't called before wait() ?
You could also use JDK's standard RunnableFuture like this:
RunnableFuture<Void> task = new FutureTask<>(runnable, null);
runOnUiThread(task);
try {
task.get(); // this will block until Runnable completes
} catch (InterruptedException | ExecutionException e) {
// handle exception
}
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