Explain Different way of Using Thread

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:

  1. Extending the Thread class: You can create a new class that extends the Thread class and override its run method. The run method contains the code that will be executed in the new thread.
    java
    class MyThread extends Thread {
    public void run() {
    // Code to be executed in the new thread
    }
    }
    // Creating and starting the thread
    MyThread myThread = new MyThread();
    myThread.start();

  2. 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
    class MyRunnable implements Runnable {
    public void run() {
    // Code to be executed in the new thread
    }
    }
    // Creating a thread using Runnable
    Thread myThread = new Thread(new MyRunnable());
    myThread.start();

    Starting a thread involves calling the start() method on an instance of the Thread class. The start() method internally calls the run() method, which should be overridden in your custom thread class or provided through the Runnable 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.