Java Thread join to wait for the finalization of a thread

Introduction

Java Thread wait for the finalization of a thread

To wait for the finalization of a thread, use the join() method of the Thread class.

When calling join() method using a thread object, it suspends the execution of the calling thread until the object called finishes its execution.


import java.util.Date;
import java.util.concurrent.TimeUnit;

public class Main {
  public static void main(String[] args) {

    // Creates and starts a MyThread1 runnable object
    MyThread1 dsLoader = new MyThread1();
    Thread thread1 = new Thread(dsLoader, "DataSourceThread");
    thread1.start();//from   w  w  w .j ava2s .co  m

    // Creates and starts a MyThread2 runnable object
    MyThread2 ncLoader = new MyThread2();
    Thread thread2 = new Thread(ncLoader, "NetworkConnectionLoader");
    thread2.start();

    // Wait for the finalization of the two threads
    try {
      thread1.join();
      thread2.join();
    } catch (InterruptedException e) {
      e.printStackTrace();
    }

    // Waits a message
    System.out.printf("Main: Configuration has been loaded: %s\n", new Date());
  }
}

class MyThread1 implements Runnable {
  @Override
  public void run() {

    // Writes a messsage
    System.out.printf("Begining data sources loading: %s\n", new Date());
    // Sleeps four seconds
    try {
      TimeUnit.SECONDS.sleep(4);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    // Writes a message
    System.out.printf("Data sources loading has finished: %s\n", new Date());
  }
}

class MyThread2 implements Runnable {
  @Override
  public void run() {
    // Writes a message
    System.out.printf("Begining network connections loading: %s\n", new Date());
    // Sleep six seconds
    try {
      TimeUnit.SECONDS.sleep(6);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    // Writes a message
    System.out.printf("Network connections loading has finished: %s\n", new Date());
  }
}



PreviousNext

Related