Saturday, April 09, 2011

How to know if all the threads you started have completed

Question : I have one object that have one method named StartDownload(), that starts three threads. How do I make to get a notification when each thread as finished the execution ?

Answer :

There are a number of ways you can do this:

  1. Use Thread.join() in your main thread to wait in a blocking fashion for each Thread to complete, or
  2. Check Thread.isAlive() in a polling fashion — generally discouraged — to wait until each Thread has completed, or
  3. Unorthodox, for each Thread in question, call setUncaughtExceptionHandler to call a method in your object, and program each Thread to throw an uncaught Exception when it completes, or
  4. Use locks or synchronizers or mechanisms from java.util.concurrent, or
  5. More orthodox, create a listener in your main Thread, and then program each of your Threads to tell the listener that they have completed.

To learn more and see code examples refer to the Stack Over Flow PAGE here

No comments: