"implements Runnable" vs "extends Thread" in Java
In Java, you can create a thread in two ways: by implementing the Runnable
interface or by extending the Thread
class.
The main difference between these two approaches is that, when you implement the Runnable
interface, your class cannot inherit from any other class because Java does not support multiple inheritance of classes. This means that you will have to use another class to create a thread and pass your Runnable
object to that class. On the other hand, if you extend the Thread
class, your class can inherit all the methods of the Thread
class and you can directly create an instance of your class and call its start()
method to start the thread.
Here is an example of how you can create a thread by implementing the Runnable
interface:
class MyRunnable implements Runnable {
public void run() {
// Your thread code goes here
}
}
// To create a thread, you need to create an instance of the Thread class
// and pass an instance of your Runnable class to the Thread's constructor
Thread thread = new Thread(new MyRunnable());
// Start the thread
thread.start();
And here is an example of how you can create a thread by extending the Thread
class:
class MyThread extends Thread {
public void run() {
// Your thread code goes here
}
}
// To create a thread, you can simply create an instance of your Thread class
MyThread thread = new MyThread();
// Start the thread
thread.start();
There are some other minor differences between the two approaches, but this is the main difference. In general, the Runnable
interface is preferred over the Thread
class because it allows you to use the Thread
class without inheriting from it, which is more flexible.