Java Multithreading - Ultimate Beginner to
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
1. 🌟 Introduction to Multitasking and Multithreading
🔹 Multitasking:
Performing multiple tasks at the same time to improve performance and
reduce response time.
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:
🔹 Method 1: Extending Thread Class
class MyThread extends Thread {
public void run() {
System.out.println("Child thread");
}
}
public class Demo {
public static void main(String[] args) {
MyThread t = new MyThread(); // Instantiate
t.start(); // Start new thread
}
}
How start() Works:
Creates a new thread (new call stack)
Registers thread with Thread Scheduler
Calls run() method internally
Note: If you call t.run() directly, it will run in the main thread like a
normal method.
🔹 Method 2: Implementing Runnable Interface
class MyRunnable implements Runnable {
public void run() {
System.out.println("Runnable thread");
}
}
public class Demo {
public static void main(String[] args) {
Runnable r = new MyRunnable();
Thread t = new Thread(r); // Pass Runnable to Thread
t.start(); // Start new thread
}
}
Why Prefer Runnable?
More flexible (Java supports only single inheritance)
Recommended for real-world applications
⚡ Difference between start() and run():
Method New Thread? Execution Type
start() Yes Multithreaded
run() No Single-threaded
3. 🌐 Getting and Setting Thread Name
Thread t = new Thread();
t.setName("MyThread");
System.out.println(t.getName());
Default names: Thread-0, Thread-1, …
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.
5. 🔒 Methods to Control Thread Execution
✈ yield():
Temporarily pauses current thread and gives chance to other threads with
same or higher priority.
⏳ 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()
These must be called inside synchronized blocks.
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!
This document serves as a comprehensive and interview-ready explanation
of Java Multithreading, from basics to advanced. Practice code examples and
try case studies to build confidence!