How to Create a Thread in Java

In Java, there are two primary ways to create a thread: by extending the Thread class or implementing the Runnable interface. Both methods allow you to define the code that should run in the thread.

Method 1: Extending the Thread Class

To create a thread by extending the Thread class, you need to follow these steps:

  1. Create a new class that extends the Thread class.
  2. Override the run() method to define the code that will be executed in the thread.
  3. Create an instance of your class and call the start() method to begin execution.

Example of Extending Thread:

Code Example 1

class MyThread extends Thread {
    public void run() {
        System.out.println("Thread is running...");
    }
}

public class ThreadCreation {
    public static void main(String[] args) {
        MyThread thread = new MyThread(); // Create a new thread
        thread.start(); // Start the thread
    }
}

Method 2: Implementing the Runnable Interface

An alternative way to create a thread is to implement the Runnable interface. This is particularly useful if your class already extends another class (since Java does not support multiple inheritance). The steps are:

  1. Create a new class that implements the Runnable interface.
  2. Override the run() method to define the code to be executed.
  3. Create an instance of the class and pass it to a Thread object. Call the start() method on the thread.

Example of Implementing Runnable:

Code Example 2

class MyRunnable implements Runnable {
    public void run() {
        System.out.println("Runnable thread is running...");
    }
}

public class RunnableThread {
    public static void main(String[] args) {
        MyRunnable myRunnable = new MyRunnable(); // Create a Runnable instance
        Thread thread = new Thread(myRunnable); // Create a thread with the Runnable
        thread.start(); // Start the thread
    }
}

Output:

Thread is running...
Runnable thread is running...

Key Points:

By mastering these methods, you can effectively create and manage threads in your Java applications, leading to improved performance and responsiveness.