Java Wait for thread to finish

Allan picture Allan · Jan 14, 2011 · Viewed 193.9k times · Source

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.

Thank you kindly.

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.

Answer

unholysampler picture unholysampler · Jan 14, 2011

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