Runnable vs. Thread

Difference

For both, you need to Override run() method to be created as a new thread by start() call.

thread runnable

implements Runnable (preferred way)

  • it shares the same object to multiple threads.
  • you can save a space for your class to extend any other class in future or now.

extends Thread

  • Each of your thread creates unique object and associate with it.
  • You can’t extend any other class which you required. (Java does not allow inheriting more than one class).

Runnable

  • You need to make Thread and put the ExampleThread in the parameter, and call .start()
public class ExampleThread implements Runnable{
   public void run(){
      System.out.println("Thread running");
   }
}

public class App{
   public static void main(String[] args){
      ExampleThread ex = new ExampleThread();
      Thread t = new Thread(ex);    // Runnable in Thread parameter
      t.start();
   }
}

thread

  • You can directly use .start(), because ExampleThread extends Thread
public class ExampleThread extends Thread{
   public void run(){
      System.out.println("Thread running");
   }
}

public class App{
   public static void main(String[] args){
      ExampleThread ex = new ExampleThread();
      ex.start();
   }
}

 

Leave A Comment

Your email address will not be published. Required fields are marked *