Member-only story
Understanding the Difference Between Thread and Runnable in Java
Java’s multithreading capabilities are a powerful feature that enables developers to create concurrent applications capable of executing multiple tasks simultaneously. Central to this functionality are the Thread class and the Runnable interface. Although both play crucial roles in the world of multithreading, they serve different purposes and have distinct use cases. In this comprehensive article, we will delve into the differences between Thread and Runnable in Java, supported by an array of detailed code examples to illustrate their usage.
The Basics:
Thread:
The Thread class, a fundamental component in Java’s multithreading paradigm, represents a thread of execution. It provides methods for creating and controlling threads. When a class extends the Thread class, it essentially becomes a thread. The actual work to be performed by the thread is defined in the run() method, which must be overridden by the class extending Thread.
Let’s consider a simple example:
class MyThread extends Thread {
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("Thread: " + i);
}
}
}
public class ThreadExample {
public static void main(String[] args) {
MyThread myThread = new MyThread();
myThread.start();
for (int i = 0; i < 5; i++) {
System.out.println("Main: " + i);
}
}
}