Java Multithreading Guide
Java Multithreading Guide
Advanced Guide
✨ Agenda
1. Introduction to Multithreading
2. Ways to Define, Instantiate, and Start a Thread
3. Getting and Setting Name of a Thread
4. Thread Priorities
5. Methods to Prevent (Stop) Thread Execution
o yield()
o join()
o sleep()
6. Synchronization
7. Inter-Thread Communication
8. Deadlock
9. Daemon Threads
Types of Multitasking:
1. Process-Based Multitasking
2. Thread-Based Multitasking
✅ Process-Based Multitasking:
Each task is an independent process.
Heavyweight - consumes more memory.
Example: Listening to music while editing code in VS Code.
Used at Operating System level.
✅ Thread-Based Multitasking:
Multiple tasks (threads) inside a single program.
Lightweight - threads share the same memory.
Example: Java game with background music, animation, and scoring
logic in separate threads.
Used at Program level.
2. 🔎 Ways to Define, Instantiate, and Start a Thread
Java provides two ways to create a thread:
4. 🔹 Thread Priorities
Each thread has a priority (1 to 10):
Thread.MIN_PRIORITY = 1
Thread.NORM_PRIORITY = 5 (default)
Thread.MAX_PRIORITY = 10
t.setPriority(Thread.MAX_PRIORITY);
Note: Thread Scheduler may or may not respect priority depending on JVM.
⏳ sleep(ms):
Pauses current thread for specific milliseconds.
Thread.sleep(1000); // 1 sec
✋ join():
Waits for a thread to die.
t.join();
6. 🔐 Synchronization
Used to handle concurrency problems when multiple threads access shared
resources.
Example:
synchronized void display() {
// critical section
}
7. ✊ Inter-Thread Communication
Used when threads want to communicate or wait for each other.
Important Methods:
wait()
notify()
notifyAll()
8. ❌ Deadlock
When two or more threads are waiting for each other to release resources
and no thread is able to proceed.
Example:
Thread A locks resource1, waits for resource2 Thread B locks resource2,
waits for resource1
9. 🚀 Daemon Threads
Threads running in background (e.g., garbage collector).
Properties:
Automatically terminates when all user threads finish.
Must be set before start():
t.setDaemon(true);
📅 Thread Lifecycle Diagram
1. New (Created)
2. Runnable (start() called)
3. Running (Thread Scheduler picks it)
4. Waiting/Blocked/Sleeping
5. Dead (run() completed or terminated)
⚠ IllegalThreadStateException
Thread t = new Thread();
t.start();
t.start(); // Exception: Thread already started!