Q- What are the difference between extends Thread and implements Runnable in java?
Example: Create thread extends Thread class.
Example: Create thread implements Runnable interface.
Extends
Thread
|
Implements
Runnable
|
We have to override run method | We must implement run method |
Inheritance: If extends thread than we can't extends another class because multiple inheritance not allowed in java |
If we implements Runnable interface than we can extends another class. |
Loosely-coupled: By extends Thread class our class become tightly coupled. |
By implements Runnable interface both Task and Executor become loosely coupled. Thread is separate form the job of Threads. |
Our class become overheated by extends thread class due to additional methods in thread class. Means inheriting all the functions of the Thread class which we may do not need | No overhead on any method because Runnable interface has no other methods then run(). |
Maintanance of code not easy. | Maintanance of code is easy. |
Functions overhead: Thread class creates a unique object and get associated with that object. So that more memory required. |
Thread
defined by implementing Runnable interface shares the same object. Multiple threads share the same objects. So that less memory is used. |
Reusability : By extends Thread in class, its contains both thread and job specific behavior code. So that once thread completes its execution , it can't be restart again. |
By implements Runnable interface, we can create a different Runnable class for a specific behavior of job. It provides the freedom to reuse the specific behavior job when required. |
Example: Create thread extends Thread class.
package com.shubh.thread.example;
/*Create thread by extending the Thread class */
class CreateThreadUsingThread extends Thread {
public void run() {
try {
/* Print the running thread */
System.out.println("Thread " + Thread.currentThread().getId() + " is running");
} catch (Exception e) {
/* Throwing an exception */
System.out.println("Exception is caught");
}
}
}
// Main Class
public class MainClass {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
CreateThreadUsingThread object = new CreateThreadUsingThread();
object.start();
}
}
}
Example: Create thread implements Runnable interface.
package com.shubh.thread.example;
/*Create thread by implementing the Runnable Interface*/
class CreateThreadUsingRunnable implements Runnable {
public void run() {
try {
// Print running thread
System.out.println("Thread " + Thread.currentThread().getId() + " is running");
} catch (Exception e) {
// Throwing an exception
System.out.println("Exception is caught");
}
}
}
// Main Class
public class MainClassRunnableTest {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
Thread object = new Thread(new CreateThreadUsingRunnable());
object.start();
}
}
}
No comments:
Post a Comment