Multithreading in Java
Multithreading lets a Java program have more than one thread of execution. Each thread follows its own sequence of instructions. Threads in the same process can share objects, so shared changes need careful coordination.
Why Do We Need This?
An application may wait for one task while another task continues. Threads can help organize this work, but starting more threads does not automatically make a program faster or make shared data safe.
Main Ideas
| Concept | What it means |
|---|---|
| Thread | Represents a thread of execution |
| Runnable | Describes a task that can be run |
| start() | Starts a new thread; calling run() directly does not |
| join() | Waits for another thread to finish |
| Synchronization | Coordinates access and visibility for shared state |
| Executor | Manages task execution separately from task submission |
Simple Working Example
Run this program on its own. All required imports and classes are included.
public class HelloWorld {
public static void main(String[] args) throws InterruptedException {
Runnable task = () -> System.out.println("Practice task completed");
Thread worker = new Thread(task);
worker.start();
worker.join();
System.out.println("Main continues");
}
}Output
Practice task completed
Main continuesstart begins the worker thread. join makes main wait until that worker finishes, so these two messages appear in the shown order. Without coordination, output from different threads may appear in different orders.
Topics in This Section
- Thread Class
- Runnable Interface
- Thread Lifecycle
- Synchronization
- Inter-thread Communication
- Deadlock
- Executor Framework
Easy Way to Remember
Separate the work to perform from how it is scheduled. Protect shared mutable state and give tasks a clear completion and cancellation plan.
See you in next page....??