Java - Wait for Runnable to finish

19,403

Solution 1

  1. myRunnable.wait() will release the lock of myRunnable and wait notify
  2. we always add a check before wait.

    //synchronized wait block
    while(myRunnable.needWait){
        myRunnable.wait();
    }
    
    //synchronized notify block
    this.needWait = false;
    myRunnable.notify();
    

Solution 2

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
}
Share:
19,403
Admin
Author by

Admin

Updated on June 09, 2022

Comments

  • Admin
    Admin almost 2 years

    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:

    1. If the background thread acquires myRunnable's lock, then shouldn't myRunnable block before it's able to call notify() ?

    2. How do I know that notify() isn't called before wait() ?