Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Wait for thread to finish

I have a thread downloading data and I want to wait until the download is finished before I load the data. Is there a standard way of doing this?

More Info:

I have a Download class that gets data from a URL (Serialized POJOs). Download is Runnable and Observable. It keeps track of the bytes downloaded and download size. I have a progress bar that displays the progress to the User. The GUI observes Download to update the progress bar.

When the POJO is downloaded I want to get it and move to the next step. Each step has to wait for the previous to finish. The problem is I cant think of a way to pause my application to wait for the download thread. Once the download is finished I want to call download.getObject() which will return the data as an object. I can then cast it and get on with the next download.

I have a helper class that manages the URLs for download and makes all of the calls to Download. This call will call getObject and do the casting. The Gui calls helper.getUser(). helper starts the thread running and I want it to 'know' when it is finished so it can return the casted object.

Any suggestions/examples? I am in the beginning stages of this design so I am willing to change it.

Update:

I followed http://download.oracle.com/javase/6/docs/api/javax/swing/SwingWorker.html#get and used modal to block until the thread finished. The code was very messy and I don't like this approach. I will keep trying to find a 'clean' way to handle the workflow of the download processes.

like image 576
Allan Avatar asked Jan 14 '11 13:01

Allan


People also ask

How do you wait for threads to finish?

The wait() and join() methods are used to pause the current thread. The wait() is used in with notify() and notifyAll() methods, but join() is used in Java to wait until one thread finishes its execution.

Does Java wait for all threads to finish?

Behind the scenes it is using default JVM's fork join pool which means that it will wait for all the threads to finish before continuing.

How do you wait for a runnable to finish?

Create an Object called lock . Then after runOnUiThread(myRunnable); , you can call lock. wait() .

Is wait () in thread class?

wait() causes current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object. In other words, this method behaves exactly as if it simply performs the call wait(0).


1 Answers

Thread has a method that does that for you join which will block until the thread has finished executing.

like image 161
unholysampler Avatar answered Sep 17 '22 20:09

unholysampler