In Java, which of the following is a correct way to create a thread?

Creating Threads in Java with Runnable Interface and Thread Class

To manage concurrent operations, Java provides the concept of threads. There are two primary ways of creating a thread in Java.

Implementing the Runnable Interface

The first method is by implementing the Runnable interface. Runnable is a functional interface that can be used to encapsulate a task to be executed in a separate thread. Here's an example:

public class MyRunnable implements Runnable {
    @Override
    public void run() {
        // Code to execute in separate thread
    }
}

// To use it
Thread thread = new Thread(new MyRunnable());
thread.start();

When a Runnable object is passed to a Thread, the thread's run() method internally calls Runnable.run().

Extending the Thread Class

The second approach is by extending the Thread class. Thread class itself implements Runnable and overrides the run() method.

public class MyThread extends Thread {
    @Override
    public void run() {
        // Code to execute in separate thread
    }
}

// To use it
MyThread thread = new MyThread();
thread.start();

Note that the start() method is used to initiate the execution of the thread.

Key Insights and Best Practices

Although both methods are valid, implementing the Runnable interface is generally favored over extending the Thread class for several reasons.

  • Firstly, Java doesn't support multiple inheritance. If you extend the Thread class, your class cannot extend any other class.

  • Secondly, the class has a single responsibility, so it's cleaner for a class to only contain the task to execute in the thread (Runnable) and not the thread mechanics.

  • Finally, since the Runnable object can be shared across multiple threads, it can be used for achieving common data sharing between threads.

Remember that the choice to use Runnable or Thread will depend on the specific requirements of your program. Be mindful of the nuances and best practices to make the most of the Java threading model.

Do you find this helpful?