
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Difference Between Thread and Runnable in Java
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.
What is a thread?
A thread is a lightweight process and a basic unit of CPU utilization that consists of a program counter, a stack, and a set of registers.
Example
The following is an example of thread in Java:
public 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(); } }
The output of the above Java program is :
Thread is running
What is runnable?
A Runnable is a functional interface that enables the compiled code of the class to run as a separate thread.
Example
The following is an example of runnable in Java:
public 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(); } }
The output of the above Java program is :
Thread is running for Runnable Implementation
Difference between Thread and Runnable
The following table provides differences between Thread and Runnable:
Sr. No. | Thread | Runnable |
---|---|---|
1 |
Thread is a class. It is used to create a thread |
Runnable is a functional interface which is used to create a thread |
2 |
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 |
More memory required |
Less memory required |
5 |
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. |