Use join() to Check if a Thread Has Finished

Use join() to Check if a Thread Has Finished

Suppose you start a thread and you want to wait for that thread to finish before you continue processing. One way is to keep checking if the thread has finished by using the isAlive() method of your thread. However, this keeps the processor busy with repetitive check of the status of the thread.

A more efficient way to do this is to use the join() method of your thread as follows:

MyThread myThread = new MyThread();myThread.start();try{	myThread.join();}catch(InterruptedException ie){}System.out.println("I'm done");

This way, the main thread is joined to myThread and waits for myThread to die. As soon as myThread dies, “I’m Done” is printed, denoting that the main thread was waiting until now.


Share the Post: