Multithreading in Java
Multithreading in Java
Real-life analogy:
Imagine you're cooking food while listening to music and downloading a file in the background these are multiple tasks
happening in parallel, just like threads in a program.
run() method contains the code you want to run in the new thread.
start() actually starts the thread and calls run() behind the scenes.
State Meaning
Timed Waiting Thread waits for a specific time (e.g., sleep, join(timeout))
1. start()
What it does: Starts a new thread and calls the run() method in the background.
2. run()
What it does: Defines the code that should run in the thread.
Note: You should not call run() directly use start() instead.
3. sleep(long milliseconds)
What it does: Puts the current thread to sleep for the given time (in ms).
4. join()
5. isAlive()
6. getName() / setName(String)
8. getPriority() / setPriority(int)
MIN_PRIORITY = 1
NORM_PRIORITY = 5
MAX_PRIORITY = 10
9. isDaemon() / setDaemon(boolean)
What it does: A daemon thread runs in the background (e.g., garbage collection) and doesn't block JVM shutdown.
10. interrupt()
12. currentThread()
13. yield()
What it does: Suggests the currently executing thread to pause and allow other threads of equal priority to execute.
Note: It's just a hint, not a guarantee. Often used in tight CPU loops to be polite.
Summary:
Method Use Case
Creates and manages threads using Java APIs (Thread, Runnable, etc.)
Keeps track of thread state, metadata, stack memory, and locks
But does not control actual CPU execution time
Instead, it relies entirely on the OS thread scheduler
The OS uses a thread scheduler algorithm. Java threads are mapped 1:1 with native OS threads using system calls like:
pthread_create() on Unix/Linux
CreateThread() on Windows
The actual scheduling algorithm depends on the OS. JVM threads benefit from these algorithms.
A. Preemptive Scheduling
Java threads on Linux run inside this structure. JVM priority hints are ignored unless nice values or sched_setscheduler
is manually adjusted.
If you set a thread priority in Java (e.g. Thread.MAX_PRIORITY), Windows may give it a better queue.
But:
On Linux, it’s usually ignored unless you change the thread policy.
On Windows, it can influence thread queue placement.
Responsibility JVM OS
Detect deadlocks ✅ ❌
Context switching ❌ ✅
Summary
JVM does not contain its own thread scheduler, but uses the OS thread scheduler instead. Java threads are managed by the
JVM and executed by the OS based on preemptive and priority-based scheduling algorithms like CFS or MLFQ.
When two or more threads try to access the same shared resource at the same time, data inconsistency can occur.
To prevent this, Java provides synchronization, which ensures that only one thread can access the critical section (shared
code/data) at a time.
Real-Life Analogy:
Think of a public washroom with a single key. Only one person can use it at a time. Others must wait.
That’s what synchronization does lock access to a shared resource until the current thread is done.
You expect 2000, but you might get 1850, 1933, etc. because both threads are modifying count at the same time.
Types of Synchronization:
Method-level
Important Notes
Summary
Deadlock in Java Threads What It Is, Why It Happens, and How to Avoid It
What is a Deadlock?
A deadlock is a situation where two or more threads are waiting for each other to release resources, but none of them ever
does. As a result, all the involved threads are stuck forever.
Real-Life Analogy
Since neither will give up what they’re holding, both are stuck this is exactly how deadlocks work in code.
Java doesn't throw a DeadlockException, but you can detect it using tools like:
jConsole
VisualVM
Thread Dump (analyze using jstack)
This avoids deadlock because if a thread can’t get both locks in time, it backs off.
The more nested locks you have, the higher the risk of deadlock.
Use ExecutorService, synchronized collections, ConcurrentHashMap, BlockingQueue, etc., which handle low-level locking
internally.
Summary
Concept Explanation
What is Deadlock? Two or more threads waiting for each other forever
Real-life Example Two people holding one spoon/fork each, waiting for the
other