Java Multithreading: Thread vs Runnable
There are two ways to implement multithreading in Java: by extending the Thread class or by implementing the Runnable interface.
- Inheriting from the Thread class involves creating a subclass that extends Thread, overriding the run() method, and defining the thread’s task within it. By creating an object of this subclass and calling the start() method, the thread can be started. This method is simple and intuitive, but because Java does not support multiple inheritance, inheriting from the Thread class means that other classes cannot be inherited.
The sample code is as follows:
public class MyThread extends Thread {
@Override
public void run() {
// 线程的任务
}
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
}
}
- Implementing the Runnable interface involves creating a class that implements the interface, overrides the run() method, defines the thread’s task within it, then creating an object of that class, passing it as a parameter to the Thread class constructor, and finally calling the start() method to start the thread. This approach helps to avoid Java’s single inheritance limitation and allows classes that implement the interface to be inherited by other classes or used as parameters.
The sample code is as follows:
public class MyRunnable implements Runnable {
@Override
public void run() {
// 线程的任务
}
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
thread.start();
}
}
Difference:
- When inheriting the Thread class, you have to directly manipulate the Thread class itself, whereas when implementing the Runnable interface, you can separate the task from the thread operation, making the code clearer and easier to maintain.
- Extending the Thread class only allows inheriting from one class, while implementing the Runnable interface enables implementing multiple interfaces. Therefore, classes implementing the Runnable interface can inherit from other classes, avoiding the limitation of single inheritance.
- When a thread object is created by inheriting the Thread class, the thread class is the object itself, while when a thread object is created by implementing the Runnable interface, the thread class is created by passing an object that implements the Runnable interface as a parameter to the constructor of the Thread class.