A Java thread could be implemented by using Runnable interface or by extending the Thread class. The Runnable is more advantageous, when you are going for multiple inheritance.
In Java, there are two main ways to create and use 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 in the new thread.java
// Creating and starting the threadclass MyThread extends Thread {
public void run() {
// Code to be executed in the new thread
}
}
MyThread myThread = new MyThread();
myThread.start(); - Implementing the Runnable interface: Another way to create threads is by implementing the
Runnable
interface. This approach is more flexible because a class can implement multiple interfaces, but Java doesn’t support multiple inheritance.java
// Creating a thread using Runnableclass MyRunnable implements Runnable {
public void run() {
// Code to be executed in the new thread
}
}
Thread myThread = new Thread(new MyRunnable());
myThread.start();Starting a thread involves calling the
start()
method on an instance of theThread
class. Thestart()
method internally calls therun()
method, which should be overridden in your custom thread class or provided through theRunnable
interface implementation.
Remember that using the second approach (implementing Runnable
) is generally preferred because it allows you to separate the thread’s behavior from the class hierarchy. It also allows you to share the same Runnable
instance among multiple threads if needed.
In addition to these basic approaches, Java also provides features like synchronization, locks, and concurrency utilities in the java.util.concurrent
package for more advanced thread handling and coordination.