Two ways exist to determine whether a thread has finished.
First, you can call isAlive( ) on the thread. This method is defined by Thread, and its general form is shown here:
final boolean isAlive( )
The isAlive( ) method returns true if the thread upon which it is called is still running. It returns false otherwise.
While isAlive( ) is useful, you can use join() to wait for a thread to finish, shown here:
final void join( ) throws InterruptedException
This method waits until the thread on which it is called terminates.
Additional forms of join( ) allow you to specify a maximum amount of time that you want to wait for the specified thread to terminate.
Here is an example that uses join( ) to ensure that the main thread is the last to stop. It also demonstrates the isAlive( ) method.
class NewThread implements Runnable {
String name;
Thread t;
NewThread(String threadname) {
name = threadname;
t = new Thread(this, name);
System.out.println("New thread: " + t);
t.start();
}
public void run() {
try {
for (int i = 5; i > 0; i--) {
System.out.println(name + ": " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println(name + " interrupted.");
}
System.out.println(name + " exiting.");
}
}
public class Main {
public static void main(String args[]) {
NewThread ob1 = new NewThread("One");
NewThread ob2 = new NewThread("Two");
NewThread ob3 = new NewThread("Three");
System.out.println("Thread One is alive: " + ob1.t.isAlive());
System.out.println("Thread Two is alive: " + ob2.t.isAlive());
System.out.println("Thread Three is alive: " + ob3.t.isAlive());
try {
System.out.println("Waiting for threads to finish.");
ob1.t.join();
ob2.t.join();
ob3.t.join();
} catch (InterruptedException e) {
System.out.println("Main thread Interrupted");
}
System.out.println("Thread One is alive: " + ob1.t.isAlive());
System.out.println("Thread Two is alive: " + ob2.t.isAlive());
System.out.println("Thread Three is alive: " + ob3.t.isAlive());
System.out.println("Main thread exiting.");
}
}
Joining the default main thread with a background thread
public class Main {
public static void main(String[] args) {
Runnable r = new Runnable() {
@Override
public void run() {
System.out.println("sleeping for 5 seconds.");
try {
Thread.sleep(5000);
} catch (Exception ie) {
}
System.out.println("Worker thread is done");
}
};
Thread thd = new Thread(r);
thd.start();
System.out.println("main thread is running.");
try {
Thread.sleep(2000);
} catch (InterruptedException ie) {
}
System.out.println("main thread is waiting for worker thread.");
try {
thd.join();
} catch (InterruptedException ie) {
}
}
}