Java Thread Class and Runnable Interface
In Java, multithreading can be achieved using the Thread class or the Runnable interface.
Let's explore these concepts in-depth.
Thread Class:
The Thread class in Java is a part of the java.lang package and provides methods to create
and control threads. You can create a thread by extending the Thread class and overriding its
run() method.
// Extending Thread class
class MyThread extends Thread {
public void run() {
// Code to be executed in a separate thread
for (int i = 0; i < 5; i++) {
System.out.println("Thread 1: " + i);
}
}
}
public class ThreadClassExample {
public static void main(String[] args) {
// Create an instance of the custom thread
MyThread thread1 = new MyThread();
// Start the thread
thread1.start();
// Code in the main thread
for (int i = 0; i < 5; i++) {
System.out.println("Main Thread: " + i);
}
}
}
Runnable Interface:
The Runnable interface is an alternative to extending the Thread class. It represents a task
that can be executed in a separate thread. You need to implement the run() method when using
Runnable.
// Implementing Runnable interface
class MyRunnable implements Runnable {
public void run() {
// Code to be executed in a separate thread
for (int i = 0; i < 5; i++) {
System.out.println("Thread 2: " + i);
}
}
}
public class RunnableInterfaceExample {
public static void main(String[] args) {
// Create an instance of the custom runnable
MyRunnable myRunnable = new MyRunnable();
// Create a thread using the runnable
Thread thread2 = new Thread(myRunnable);
// Start the thread
thread2.start();
// Code in the main thread
for (int i = 0; i < 5; i++) {
System.out.println("Main Thread: " + i);
}
}
}
Choosing Between Thread Class and Runnable Interface:
-
Extending Thread: Use when you want to specialize the behavior of a thread, or when the class
is closely associated with the thread's behavior (e.g.,
Threadsubclasses). - Implementing Runnable: Use when you want to represent a task that can be executed by a thread, and the class doesn't need to specialize thread behavior.
Note:
Both methods of creating threads are widely used, and the choice depends on the specific requirements of the application.