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
Blogs
Kotlin Interview: Top Questions and Answers for Success
Deploying a PHP Application on VPS: Step-by-Step Guide
JavaScript vs Python: What to Choose for Backend? Practical Comparison on Node.js
Two Question Marks in C#: What It Is and How to Use It