⚙️ 🔥 Multithreading Example in Java
✅ Goal:
We’ll create two threads:
-
One prints numbers
-
One prints letters
→ both run concurrently
📜 Java Code:
public class MultiThreadExample {
public static void main(String[] args) {
// Thread 1: Prints numbers
Thread numberThread = new Thread(() -> {
for (int i = 1; i <= 5; i++) {
System.out.println("Number: " + i);
try { Thread.sleep(500); } catch (InterruptedException e) {}
}
});
// Thread 2: Prints letters
Thread letterThread = new Thread(() -> {
for (char c = 'A'; c <= 'E'; c++) {
System.out.println("Letter: " + c);
try { Thread.sleep(500); } catch (InterruptedException e) {}
}
});
// Start both threads
numberThread.start();
letterThread.start();
}
}🧠 What’s Happening?
-
Each
Threadruns a separate task. -
Both threads share the CPU and run concurrently.
-
Thread.sleep(500)gives each thread a little breathing room so you can actually see the switching.
🖥️ Sample Output (non-deterministic):
Number: 1
Letter: A
Number: 2
Letter: B
Letter: C
Number: 3
...
- The output order may vary each time you run it — that’s multithreading in action.
✅ Why It’s a Real Multithreaded Example
| Feature | How It Applies |
|---|---|
| 🚀 Concurrency | Two threads run at the same time |
| 🧠 Shared context | Both threads run inside the same process |
| ⏱️ Asynchronous behavior | Output order depends on OS thread scheduling |