Java Thread create a Thread

Introduction

We create a thread in two ways:

  • implement the Runnable interface.
  • extend the Thread class, itself.

Implementing Runnable

Here is an example that creates a new thread and starts it running:


class MyThread implements Runnable {

  MyThread() {/*from w  w  w  . ja  v a2s  .  c om*/
    System.out.println("Child thread" );
  }

  // This is the entry point for the second thread.
  public void run() {
    try {
      for (int i = 5; i > 0; i--) {
        System.out.println("Child Thread: " + i);
        Thread.sleep(500);
      }
    } catch (InterruptedException e) {
      System.out.println("Child interrupted.");
    }
    System.out.println("Exiting child thread.");
  }
}

public class Main {
  public static void main(String args[]) {
    Thread t = new Thread(new MyThread(), "Demo Thread");

    try {
      for (int i = 5; i > 0; i--) {
        System.out.println("Main Thread: " + i);
        Thread.sleep(1000);
      }
    } catch (InterruptedException e) {
      System.out.println("Main thread interrupted.");
    }
    System.out.println("Main thread exiting.");
  }
}

Extending Thread

class MyThread extends Thread {

  MyThread() {/*  w w  w.  j a va2 s  .  c o m*/
    super("Demo Thread");
    System.out.println("Child thread: " + this);
    start(); // Start the thread
  }
  // This is the entry point for the second thread.
  public void run() {
    try {
      for(int i = 5; i > 0; i--) {
        System.out.println("Child Thread: " + i);
        Thread.sleep(500);
      }
    } catch (InterruptedException e) {
      System.out.println("Child interrupted.");
    }
    System.out.println("Exiting child thread.");
  }
}

public class Main {
  public static void main(String args[]) {
    new MyThread(); // create a new thread

    try {
      for(int i = 5; i > 0; i--) {
        System.out.println("Main Thread: " + i);
        Thread.sleep(1000);
      }
    } catch (InterruptedException e) {
      System.out.println("Main thread interrupted.");
    }
    System.out.println("Main thread exiting.");
  }
}



PreviousNext

Related