Sobes.tech
Junior — Middle

Explain the differences between the Runnable interface and the Thread class in Java.

sobes.tech AI

Answer from AI

In Java, the Runnable interface and the Thread class are used to create threads, but there are important differences between them:

  • Runnable is a functional interface with the run() method, which describes the task that the thread should execute. A class implementing Runnable can be passed to the Thread constructor.
  • Thread is a class that represents the thread of execution itself. It can be extended (inherited) to override the run() method, or use a Runnable to perform the task.

Using Runnable is preferable because Java does not support multiple inheritance, and if a class already inherits from another class, it cannot inherit from Thread. Example:

class MyTask implements Runnable {
    public void run() {
        System.out.println("Task is running in the thread");
    }
}

public class Main {
    public static void main(String[] args) {
        Thread thread = new Thread(new MyTask());
        thread.start();
    }
}

Thus, Runnable separates the task from the thread, providing greater flexibility.

Explain the differences between the Runnable… - sobes.tech