How to implement Thread in Java?

How to implement Thread in Java?

In Java, you can create and execute threads in two primary ways: by extending the Thread class or by implementing the Runnable interface. Both approaches allow you to define the code that the thread will execute by overriding the run method.

 Thread in Java

Extending the Thread Class

   When you extend the Thread class, you create a new class that inherits from Thread and override the run method to define the thread’s task.

Implementing the Runnable Interface

   When you implement the Runnable interface, you define the run method in a separate class and pass an instance of this class to a Thread object.

Method 1: Extending the Thread in Java Class

Example
java
class MyThread extends Thread {
    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println(Thread.currentThread().getId() + " Value: " + i);
            try {
                Thread.sleep(500); // Sleep for 500 milliseconds
            } catch (InterruptedException e) {
                System.out.println(e);
            }
        }
    }
}

public class ThreadExample1 {
    public static void main(String[] args) {
        MyThread t1 = new MyThread();
        t1.start();
    }
}

Example

Method 2: Implementing the Runnable Interface

java
class MyRunnable implements Runnable {
    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println(Thread.currentThread().getId() + " Value: " + i);
            try {
                Thread.sleep(500); // Sleep for 500 milliseconds
            } catch (InterruptedException e) {
                System.out.println(e);
            }
        }
    }
}

public class ThreadExample2 {
    public static void main(String[] args) {
        Thread t1 = new Thread(new MyRunnable());
        t1.start();
    }
}

Detailed Explanation Thread in Java

  1. Extending the Thread Class:
  • Pros
    • Simple and straightforward.
    • Directly uses Thread class methods.
  • Cons:
    • Since Java does not support multiple inheritance, you cannot extend any other class.

Implementing the Runnable Interface

  • Pros:
    • More flexible as the class can extend another class.
    • Encourages decoupling of task logic and thread management.
  • Cons:
    • Slightly more verbose due to the need to pass Runnable instance to Thread.

Homepage

Readmore