Imagine a restaurant with only one person. This person has to take the order, cook the food, wash the dishes, and serve the drinks. Customers would wait forever!
In a Multithreaded restaurant, you have:
One thread (the Waiter) taking orders.
One thread (the Chef) cooking.
One thread (the Busser) cleaning.
They all work simultaneously. In Java, a Thread is a small unit of a process. By using multiple threads, you can perform heavy tasks in the background (like saving a file) without freezing the user interface.
How to Create a Thread
There are two main ways, but the most common is implementing the Runnable interface. This is basically a "Task" that you hand over to a Thread to execute.
The Code Example:
// 1. Define the Task
class KitchenTask implements Runnable {
private String taskName;
public KitchenTask(String name) {
this.taskName = name;
}
@Override
public void run() {
for (int i = 1; i <= 3; i++) {
System.out.println(taskName + " is in progress... (Step " + i + ")");
try {
// Pause for 1 second to simulate real work
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println(taskName + " was interrupted!");
}
}
System.out.println("DONE: " + taskName);
}
}
public class MultithreadingDemo {
public static void main(String[] args) {
System.out.println("--- Restaurant Opening ---");
// 2. Create the tasks
Thread chefThread = new Thread(new KitchenTask("Cooking Pizza"));
Thread waiterThread = new Thread(new KitchenTask("Serving Drinks"));
// 3. Start the threads
// Notice we call .start(), NOT .run()!
chefThread.start();
waiterThread.start();
System.out.println("Main thread: I'm free to do other things while they work!");
}
}Expected Output
(Note: The order might vary slightly because both threads are running at the same time!)
--- Restaurant Opening ---
Main thread: I'm free to do other things while they work!
Cooking Pizza is in progress... (Step 1)
Serving Drinks is in progress... (Step 1)
Cooking Pizza is in progress... (Step 2)
Serving Drinks is in progress... (Step 2)
Cooking Pizza is in progress... (Step 3)
Serving Drinks is in progress... (Step 3)
DONE: Cooking Pizza
DONE: Serving DrinksMultithreading is essential for:
Responsibility: Keeping an app responsive while it loads data.
Performance: Using all the cores of a modern CPU (most computers have 4, 8, or 16 cores).
Web Servers: Handling thousands of users at once.
The "Thread Safety" Warning: When two threads try to change the same variable at the exact same time (like two people trying to withdraw the last $10 from a bank account), things can get messy. This is called a Race Condition, and professional developers use "Synchronization" to prevent it.