Create New Thread Using Runnable - Java Thread

Java examples for Thread:Thread Operation

Description

Create New Thread Using Runnable

Demo Code


public class Main implements Runnable {
  public void run() {

    for (int i = 0; i < 5; i++) {
      System.out.println("Child Thread : " + i);

      try {/*from   w  ww.  ja  v  a 2  s. c o m*/
        Thread.sleep(50);
      } catch (InterruptedException ie) {
        System.out.println("Child thread interrupted! " + ie);
      }
    }

    System.out.println("Child thread finished!");
  }

  public static void main(String[] args) {
    Thread t = new Thread(new Main(), "My Thread");
    t.start();
    for (int i = 0; i < 5; i++) {

      System.out.println("Main thread : " + i);

      try {
        Thread.sleep(100);
      } catch (InterruptedException ie) {
        System.out.println("Child thread interrupted! " + ie);
      }
    }
    System.out.println("Main thread finished!");
  }
}

Result


Related Tutorials