Java Thread join multiple threads

Introduction

To wait for a thread to finish is called join():

final void join() throws InterruptedException 

join() waits until the thread on which it is called terminates.

class MyThread extends Thread {
  int[] a;/*from  w  w  w  .  j  a va 2  s .  c o  m*/

  MyThread(int[] ar) {
    a = ar;
    start();
  }

  public void run() {
    java.util.Arrays.sort(a);
    System.out.println("Child completed sorting.");
  }
}

public class Main {
  public static void main(String args[]) throws Exception {
    int a[] = { 2, 6, 4, 0, 1, 5, 3 };
    MyThread t = new MyThread(a);
    t.join();
    System.out.println("Main printing array elements are :");
    for (int i = 0; i < a.length; i++)
      System.out.print(a[i] + " ");
  }
}

// Using join() to wait for threads to finish.
class MyThread implements Runnable {
  String name; // name of thread
  Thread t;/*from   w  w w  .j a va2s.  c  om*/

  MyThread(String threadname) {
    name = threadname;
    t = new Thread(this, name);
    System.out.println("New thread: " + t);
    t.start(); // Start the thread
  }

  // This is the entry point for thread.
  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[]) {
    MyThread thread1 = new MyThread("One");
    MyThread thread2 = new MyThread("Two");
    MyThread thread3 = new MyThread("Three");

    System.out.println("Thread One is alive: " + thread1.t.isAlive());
    System.out.println("Thread Two is alive: " + thread2.t.isAlive());
    System.out.println("Thread Three is alive: " + thread3.t.isAlive());
    // wait for threads to finish
    try {
      System.out.println("Waiting for threads to finish.");
      thread1.t.join();
      thread2.t.join();
      thread3.t.join();
    } catch (InterruptedException e) {
      System.out.println("Main thread Interrupted");
    }

    System.out.println("Thread One is alive: " + thread1.t.isAlive());
    System.out.println("Thread Two is alive: " + thread2.t.isAlive());
    System.out.println("Thread Three is alive: " + thread3.t.isAlive());
    System.out.println("Main thread exiting.");
  }
}



PreviousNext

Related