February 8, 2011

Java Threads Basic Example

Creating a new thread of execution by extending the Thread class

public class MyThread extends Thread {

   public void run() {
      for(int i=0; i<20; i++) {
         System.out.println("In thread: " + Thread.currentThread().getName());
      }
   }
}

public class Driver {

   public static void main(String[] args) {

      MyThread t = new MyThread();
      t.setName("MyThread");
      t.start();

      for(int i=0; i<20; i++) {
         System.out.println("In thread: " + Thread.currentThread().getName());
      }
   }
}

Creating a new thread of execution by implementing the Runnable interface

public class MyRunnable implements Runnable {

   public void run() {
      for(int i=0; i<20; i++) {
         System.out.println("In thread: " + Thread.currentThread().getName());
      }
   }
}

public class Driver {

   public static void main(String[] args) {

      MyRunnable r = new MyRunnable();
      Thread t = new Thread(r);
      t.setName("MyRunnable");
      t.start();

      for(int i=0; i<20; i++) {
         System.out.println("In thread: " + Thread.currentThread().getName());
      }
   }
}

The second method (implementing Runnable) is preferred over the first method (extending Thread)

No comments:

Post a Comment