Multithreading in Java - Complete Notes
1. What is Multithreading?
Multithreading is a core concept in Java where multiple threads (lightweight subprocesses) run concurrently.
It improves performance by allowing multitasking within a single program.
2. Thread Creation Methods
- Extending Thread class: Create a class that extends Thread and override run().
- Implementing Runnable interface: Implement Runnable, override run(), and pass it to a Thread object.
3. Thread Lifecycle
States: New - Runnable - Running - Waiting/Blocked - Terminated.
Control methods: start(), sleep(), join(), isAlive().
4. Thread Priority
Java threads have priorities (1 to 10). JVM uses priority as a scheduling hint.
MIN_PRIORITY (1), NORM_PRIORITY (5 - default), MAX_PRIORITY (10).
5. Synchronization
Prevents multiple threads from accessing shared resources simultaneously.
Use synchronized methods or blocks to avoid race conditions.
6. Inter-Thread Communication
Used for coordination between threads. Methods: wait(), notify(), notifyAll().
Must be used inside synchronized blocks. Useful for producer-consumer problems.
7. Concurrency
Concurrency means multiple tasks are in progress at once. Java achieves concurrency using threads.
Java provides advanced tools like ExecutorService, Callable, Future for better concurrency control.
Multithreading in Java - Complete Notes
8. Thread with Applet
Applets can use threads for animations or timers. Use init() to start the thread, run() for logic, and paint() to
update the display.
Example: A counter applet updating every second.
9. Key Differences
- Concurrency vs Parallelism: Concurrency = tasks in progress, Parallelism = truly simultaneous tasks.
- Multithreading vs Multiprocessing: Multithreading = one process, multiple threads; Multiprocessing =
multiple processes.