Difference between Thread and Runnable in Java

JavaObject Oriented ProgrammingProgramming

There are two ways to create a new thread of execution. One is to declare a class to be a subclass of the Thread class. This subclass should override the run method of the Thread class. An instance of the subclass can then be allocated and started.

The other way to create a thread is to declare a class that implements the Runnable interface. That class then implements the run method. An instance of the class can then be allocated, passed as an argument when creating Thread, and started.

Every thread has a name for identification purposes. More than one thread may have the same name. If a name is not specified when a thread is created, a new name is generated for it.

Sr. No.KeyThreadRunnable
1
Basic 
Thread is a class. It is used to create a thread 
Runnable is a functional interface which is used to create a thread 
2
Methods
It has multiple methods including start() and run()
It has only abstract method run()
3
 Each thread creates a unique object and gets associated with it
Multiple threads share the same objects.
4
Memory 
More memory required 
Less memory required 
5
Limitation 
Multiple Inheritance is not allowed in java hence after a class extends Thread class, it can not extend any other class
If a class is implementing the runnable interface then your class can extend another class.

Example of Runnable

class RunnableExample implements Runnable{
   public void run(){
      System.out.println("Thread is running for Runnable Implementation");
   }
   public static void main(String args[]){
      RunnableExample runnable=new RunnableExample();
      Thread t1 =new Thread(runnable);
      t1.start();
   }
}

Example of Thread

class ThreadExample extends Thread{
   public void run(){
      System.out.println("Thread is running");
   }
   public static void main(String args[]){
      ThreadExample t1=new ThreadExample ();
      t1.start();
   }
}
raja
Published on 18-Nov-2019 06:58:13
Advertisements