Thread class and Runnable interface can be used to create threads and using Runnable interface is the most advantageous method to create threads because we need not extend thread class here.
In Core Java, the primary classes and interfaces used to create threads are:
- Thread class: The
Thread
class itself is used to create and manage threads. You can extend theThread
class and override itsrun()
method to define the code that will be executed by the thread.Example:
javaclass MyThread extends Thread {
public void run() {
// Code to be executed by the thread
}
}
- Runnable interface: The
Runnable
interface can be implemented by a class whose instances are intended to be executed by a thread. This interface provides arun()
method that should be implemented to define the code to be executed by the thread.Example:
javaclass MyRunnable implements Runnable {
public void run() {
// Code to be executed by the thread
}
}
The most advantageous method for creating threads in Java is generally considered to be implementing the Runnable
interface. This is because Java supports single inheritance, and if you extend the Thread
class to create a new thread, you cannot extend any other class. However, if you implement the Runnable
interface, you can still extend another class, and the class can be used to create multiple threads.
Example of using Runnable
:
public class Main {
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread myThread = new Thread(myRunnable);
myThread.start();
}
}
This approach promotes better design practices and is generally considered more flexible.