Multithreading Programs
Multithreading can feel abstract at first — hands-on practice with simple thread examples helps make the concept concrete.
Why practice these?
Multithreading can feel abstract at first — hands-on practice with simple thread examples helps make the concept concrete.
Program 1: Two Threads Printing Simultaneously
javaclass NumberPrinter extends Thread { public void run() { for (int i = 1; i <= 3; i++) { System.out.println(Thread.currentThread().getName() + ": " + i); } } } public class MultipleThreadsDemo { public static void main(String[] args) { NumberPrinter t1 = new NumberPrinter(); NumberPrinter t2 = new NumberPrinter(); t1.start(); t2.start(); } }
Output (order may vary between runs):
Thread-0: 1
Thread-1: 1
Thread-0: 2
Thread-1: 2
Thread-0: 3
Thread-1: 3Program 2: Using Runnable with a Lambda
javapublic class RunnableLambdaDemo { public static void main(String[] args) { Runnable task = () -> System.out.println("Task executed by: " + Thread.currentThread().getName()); Thread t = new Thread(task); t.start(); } }
Output:
Task executed by: Thread-0Key Points to Remember
- Thread execution order is not guaranteed — running the same program twice may show a different interleaving of output.
- Practicing with small thread examples helps build intuition before tackling synchronization and thread pools.
- Using lambda expressions with
Runnableis a common, concise style in modern Java code.