Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Wait for Runnable to finish

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() ?

like image 906
ThrowAway43616 Avatar asked Dec 25 '15 01:12

ThrowAway43616


1 Answers

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
}
like image 128
Gediminas Rimsa Avatar answered Oct 21 '22 00:10

Gediminas Rimsa