A thread class may be declared as a subclass of Thread, or it may implement the Runnable interface.
In Java, there are two basic ways to define classes that can be run as threads:
- Extending the Thread class: You can create a new class that extends the
Thread
class and override itsrun()
method. Therun()
method contains the code that will be executed when the thread is started. Here’s an example:java
public static void main(String[] args) {public class MyThread extends Thread {
public void run() {
// Code to be executed by the thread
}
MyThread myThread = new MyThread();
myThread.start(); // This starts the execution of the run() method in a new thread
}
} - Implementing the Runnable interface: Alternatively, you can create a class that implements the
Runnable
interface. This interface has a single method,run()
, which you need to override. The advantage of this approach is that it allows you to extend another class if needed, as Java supports multiple interface implementations. Here’s an example:java
public static void main(String[] args) {public class MyRunnable implements Runnable {
public void run() {
// Code to be executed by the thread
}
Thread myThread = new Thread(new MyRunnable());
myThread.start(); // This starts the execution of the run() method in a new thread
}
}
Both approaches allow you to define the behavior that will be executed in a separate thread of execution. The second approach (implementing Runnable
) is often preferred as it provides more flexibility in terms of class hierarchy and is considered good practice in Java.