In Java: implements Runnable vs extends Thread — which to choose for creating a thread?
Hello everyone! I started learning multithreading in Java and got confused about two approaches to creating threads. Everywhere it says that you can either extend the Thread class or implement the Runnable interface. But when to use what?
Here are the examples I tried:
1) extends Thread:
```java
class MyThread extends Thread {
public void run() {
System.out.println("Thread is running");
}
}
public class Main {
public static void main(String[] args) {
MyThread t = new MyThread();
t.start();
}
}
```
2) implements Runnable:
```java
class MyRunnable implements Runnable {
public void run() {
System.out.println("Thread is running");
}
}
public class Main {
public static void main(String[] args) {
MyRunnable task = new MyRunnable();
Thread t = new Thread(task);
t.start();
}
}
```
Both options work — I checked. But what is the difference? Why do textbooks recommend using Runnable? And can I
No answers yet.
Log in to leave an answer