Skip to content

Latest commit

 

History

History
86 lines (64 loc) · 2.38 KB

02. isAlive() and join().md

File metadata and controls

86 lines (64 loc) · 2.38 KB

isAlive() and join()

  • Two ways of determining if the thread has finished
  1. isAlive()

    • final boolean isAlive()
    • returns true if running else false.
  2. join()

    • final void join() throws InterruptedException
    • wait until the thread on which the method is called terminates.
    • Also allows you to specify a maximum amount of time that you want to wait for the specified thread to terminate.

using join() to wait for the threads to finish

class CustomThread extends Thread {

    CustomThread(String name){
        super(name);
    }

    /**
     * Runs this operation.
     */
    @Override
    public void run() {
        try {
            for(int n=3;n>0;n--){
                System.out.println("thread " + this.getName() +" >> " +  n);
                Thread.sleep(500);
            }
        }catch (InterruptedException ex){
            System.out.println("thread " + this.getName() + " interrupted");
        }
        System.out.println("thread " + this.getName() + " exiting");
    }
}

public class Main {

    public static void main(String[] args) {
        Thread t = Thread.currentThread();

        System.out.println("main thread: " + t);

        CustomThread t1 = new CustomThread("t1");
        CustomThread t2 = new CustomThread("t2");
        CustomThread t3 = new CustomThread("t3");
        CustomThread t4 = new CustomThread("t4");

        t1.start();
        t2.start();
        t3.start();
        t4.start();

        System.out.println(t1.getName() + " is alive: " + t1.isAlive());
        System.out.println(t2.getName() + " is alive: " + t2.isAlive());
        System.out.println(t3.getName() + " is alive: " + t3.isAlive());
        System.out.println(t4.getName() + " is alive: " + t4.isAlive());

        try {

            System.out.println("main thread: waiting for the threads to finish");
            t1.join();
            t2.join();
            t3.join();
            t4.join();

        }catch (InterruptedException ex){
            System.out.println("main thread interrupted");
        }

        System.out.println(t1.getName() + " is alive: " + t1.isAlive());
        System.out.println(t2.getName() + " is alive: " + t2.isAlive());
        System.out.println(t3.getName() + " is alive: " + t3.isAlive());
        System.out.println(t4.getName() + " is alive: " + t4.isAlive());
        System.out.println("Main thread exiting");
    }
}