In Java multithreading, a task can be executed either by extending the Thread class or by implementing the Runnable interface. Both approaches create concurrent execution paths, but they differ in design, flexibility, and best practices.
java.lang.Thread and override run()java.lang.Runnable and pass it to a Thread
// Creating a thread by extending Thread class
class MyThread extends Thread {
public void run() {
// Code executed when thread starts
System.out.println("Thread running using Thread class");
}
}
public class ThreadExample {
public static void main(String[] args) {
// Creating and starting thread
MyThread t1 = new MyThread();
t1.start();
}
}
// Creating a task using Runnable interface
class MyTask implements Runnable {
public void run() {
// Code executed when thread starts
System.out.println("Thread running using Runnable");
}
}
public class RunnableExample {
public static void main(String[] args) {
// Passing task to Thread object
Thread t1 = new Thread(new MyTask());
t1.start();
}
}
In Java, when you start multiple threads (whether via Thread or Runnable), the Thread Scheduler decides who runs when. Execution order is not guaranteed! Click "Start" to see them race.
Both programs will print a message from a separate thread. The execution order may vary because thread scheduling depends on the JVM and OS.
Thread.currentThread().getName()