Multithreading in Java is a feature that lets a program run multiple threads at the same time, so tasks can work in parallel and use the CPU more efficiently. A thread is simply a smaller, lightweight unit of a program that runs independently but within the same process.
Example: Suppose a restaurant kitchen where multiple chefs are working simultaneously on different dishes. This setup ensures faster service and better CPU (chef) utilization, just like threads in Java.
Concurrent ExecutionImplementation:
Java
class CookingTask extends Thread {
private String task;
CookingTask(String task) {
this.task = task;
}
public void run() {
System.out.println(task + " is being prepared by " +
Thread.currentThread().getName());
}
}
public class Restaurant {
public static void main(String[] args) {
Thread t1 = new CookingTask("Pasta");
Thread t2 = new CookingTask("Salad");
Thread t3 = new CookingTask("Dessert");
Thread t4 = new CookingTask("Rice");
t1.start();
t2.start();
t3.start();
t4.start();
}
}
OutputDessert is being prepared by Thread-2
Salad is being prepared by Thread-1
Rice is being prepared by Thread-3
Pasta is being prepared by Thread-0
Explanation:
- The program creates multiple threads by extending the Thread class (CookingTask).
- Each thread represents a dish being prepared (e.g., Pasta, Salad, etc.).
- Threads t1 to t4 are started using .start(), allowing tasks to run concurrently.
Different Ways to Create Threads
Threads can be created by using two mechanisms:
1. Extending the Thread class: We create a class that extends Thread and override its run() method to define the task. Then, we make an object of this class and call start(), which automatically calls run() and begins the thread’s execution.
2. Implementing the Runnable Interface: We create a new class which implements java.lang.Runnable interface and define the run() method there. Then we instantiate a Thread object and call start() method on this object.
Note: Extend Thread when when you don’t need to extend any other class. Implement Runnable when your class already extends another class (preferred in most cases).
Multithreading Introduction
Multithreading in Java
Explore
Basics
OOPs & Interfaces
Collections
Exception Handling
Java Advanced
Practice Java