Multithreading is a powerful tool that can improve the performance and responsiveness of our Java applications. However, when it comes to implementing multithreading, we're faced with a choice: should we extend the Thread class or should we implement the Runnable interface? In this blog post, we'll dive into the details of both approaches and compare them side-by-side to help you make the right decision.
Overview of Thread and Runnable
Extending Thread class
When you extend the Thread class, you're creating a new class that inherits all the properties and methods of the Thread class, including the run() method, which you can override with the code you want the thread to execute:
public class ThreadExample extends Thread {
// run() method contains the code that is executed by the thread.
@Override
public void run() {
System.out.println("Inside : " + Thread.currentThread().getName());
}
}
After creating the class, you can instantiate and start the thread like so:
Thread thread = new ThreadExample();
thread.start();
Implementing Runnable interface
On the other hand, the Runnable interface provides a single method, run(), that you must implement to define the code the thread will execute:
public class RunnableExample implements Runnable {
@Override
public void run() {
System.out.println("Inside : " + Thread.currentThread().getName());
}
}
After implementing the Runnable interface, you can create a runnable instance and pass it to the Thread instance:
Runnable runnable = new RunnableExample();
Thread thread = new Thread(runnable);
thread.start();
Comparison
Let's compare these two options based on some key factors:1. Inheritance:
2. Code Separation:
3. Object Sharing:
4. Overhead:
5. Use Lambda Expressions:
Runnable runnable = () -> {
System.out.println("Inside : " + Thread.currentThread().getName());
};
System.out.println("Creating Thread...");
Thread thread = new Thread(runnable);
System.out.println("Starting Thread...");
thread.start();
Comments
Post a Comment
Leave Comment