In Java: implements Runnable vs extends Thread — which to choose?
Hello everyone! I started learning multithreading in Java and got confused about a basic point. We create threads in two ways: either by extending the Thread class or by implementing the Runnable interface. Both seem to work, but I don't understand the fundamental difference and which way is considered correct.
For example, I wrote this code:
```java
// Way 1: extends Thread
class MyThread extends Thread {
public void run() {
System.out.println("Thread is running: " + Thread.currentThread().getName());
}
}
// Way 2: implements Runnable
class MyRunnable implements Runnable {
public void run() {
System.out.println("Thread is running: " + Thread.currentThread().getName());
}
}
public class Main {
public static void main(String[] args) {
MyThread t1 = new MyThread();
t1.start();
Thread t2 = new Thread(new MyRunnable());
t2.start();
}
}
```
Both options give the same result. But I heard that implements
No answers yet.
Log in to leave an answer