Using isAlive( ) and join( )
1.isAlive()
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.
class first implements Runnable { Thread t; first(String name) { t = new Thread(this, name); t.start(); } public void run() { System.out.println("T" + t); } } public class IsAliveExample { public static void main(String[] args) { System.out.println("Main thread is alive " + Thread.currentThread().isAlive()); Thread t1 = new Thread(new first("First Thread")); System.out.println("is t1 alive " + t1.isAlive()); // executed and // closed in above // line Thread t2 = new Thread(new first("Second Thread")); } }
2.join
While isAlive( ) is occasionally useful, the method that you will more commonly use to wait for a thread to finish is called join( ), shown here:
final void join( ) throws InterruptedException
This method waits until the thread on which it is called terminates.Example is as follows :
class Callme { void call(String msg) { System.out.print("Start " + msg); try { Thread.sleep(1000); } catch (InterruptedException e) { System.out.println("Interrupted"); } System.out.println(" End"); } } class Caller implements Runnable { String msg; Callme target; Thread t; public Caller(Callme targ, String s) { target = targ; msg = s; t = new Thread(this); t.start(); } public void run() { synchronized (target) { // synchronized block target.call(msg); } } } public class example5 { public static void main(String args[]) { Callme target = new Callme(); Caller ob1 = new Caller(target, "A"); Caller ob2 = new Caller(target, "B"); Caller ob3 = new Caller(target, "C"); // wait for threads to end try { System.out.println(ob1.t.isAlive()); ob1.t.join(); ob2.t.join(); ob3.t.join(); } catch (Exception e) { System.out.println("Interrupted"); } } }