Multithreading in Java. CPU _ by Engineering Digest _ Medium (1)
Multithreading in Java. CPU _ by Engineering Digest _ Medium (1)
Get unlimited access to the best of Medium for less than $1/week. Become a member
Multithreading in Java
Engineering Digest · Follow
17 min read · Aug 2, 2024
CPU
The CPU, often referred to as the brain of the computer, is responsible for executing
instructions from programs. It performs basic arithmetic, logic, control, and
input/output operations specified by the instructions.
Core
https://engineeringdigest.medium.com/multithreading-in-java-39f34724bbf6 1/33
08/02/2025, 11:21 Multithreading in Java. CPU | by Engineering Digest | Medium
A core is an individual processing unit within a CPU. Modern CPUs can have
multiple cores, allowing them to perform multiple tasks simultaneously.
Program
Microsoft Word is a program that allows users to create and edit documents.
Process
Thread
A thread is the smallest unit of execution within a process. A process can have
multiple threads, which share the same resources but can run independently.
A web browser like Google Chrome might use multiple threads for different tabs,
with each tab running as a separate thread.
Multitasking
Example: We are browsing the internet while listening to music and downloading a file.
https://engineeringdigest.medium.com/multithreading-in-java-39f34724bbf6 2/33
08/02/2025, 11:21 Multithreading in Java. CPU | by Engineering Digest | Medium
Multitasking utilizes the capabilities of a CPU and its cores. When an operating
system performs multitasking, it can assign different tasks to different cores. This is
more efficient than assigning all tasks to a single core.
Multithreading
A web browser can use multithreading by having separate threads for rendering the
page, running JavaScript, and managing user inputs. This makes the browser more
responsive and efficient.
In a single-core system:
Both threads and processes are managed by the OS scheduler through time slicing
and context switching to create the illusion of simultaneous execution.
In a multi-core system:
Both threads and processes can run in true parallel on different cores, with the OS
scheduler distributing tasks across the cores to optimize performance.
Time Slicing
Definition: Time slicing divides CPU time into small intervals called time slices
or quanta.
Function: The OS scheduler allocates these time slices to different processes and
threads, ensuring each gets a fair share of CPU time.
Purpose: This prevents any single process or thread from monopolizing the
CPU, improving responsiveness and enabling concurrent execution.
Context Switching
https://engineeringdigest.medium.com/multithreading-in-java-39f34724bbf6 3/33
08/02/2025, 11:21 Multithreading in Java. CPU | by Engineering Digest | Medium
Purpose: This allows multiple processes and threads to share the CPU, giving the
appearance of simultaneous execution on a single-core CPU or improving
parallelism on multi-core CPUs.
Multitasking can be achieved through multithreading where each task is divided into
threads that are managed concurrently.
Multithreading in Java
Java provides robust support for multithreading, allowing developers to create
applications that can perform multiple tasks simultaneously, improving
performance and responsiveness.
The threads share the single core, and time-slicing is used to manage thread
execution.
The JVM can distribute threads across multiple cores, allowing true parallel
execution of threads.
https://engineeringdigest.medium.com/multithreading-in-java-39f34724bbf6 4/33
08/02/2025, 11:21 Multithreading in Java. CPU | by Engineering Digest | Medium
When a Java program starts, one thread begins running immediately, which is
called the main thread. This thread is responsible for executing the main method of
a program.
To create a new thread in Java, you can either extend the Thread class or implement
the Runnable interface.
2. The run method is overridden to define the code that constitutes the new
thread.
https://engineeringdigest.medium.com/multithreading-in-java-39f34724bbf6 5/33
08/02/2025, 11:21 Multithreading in Java. CPU | by Engineering Digest | Medium
}
}
2. The run method is overridden to define the code that constitutes the new
thread.
4. start method is called on the Thread object to initiate the new thread.
Thread Lifecycle
The lifecycle of a thread in Java consists of several states, which a thread can move
through during its execution.
New: A thread is in this state when it is created but not yet started.
https://engineeringdigest.medium.com/multithreading-in-java-39f34724bbf6 6/33
08/02/2025, 11:21 Multithreading in Java. CPU | by Engineering Digest | Medium
Runnable: After the start method is called, the thread becomes runnable. It’s
ready to run and is waiting for CPU time.
Runnable vs Thread
Use Runnable when you want to separate the task from the thread, allowing the
class to extend another class if needed. Extend Thread if you need to override
Thread methods or if the task inherently requires direct control over the thread
itself, though this limits inheritance.
Thread methods
1. start( ): Begins the execution of the thread. The Java Virtual Machine (JVM) calls
the run() method of the thread.
https://engineeringdigest.medium.com/multithreading-in-java-39f34724bbf6 7/33
08/02/2025, 11:21 Multithreading in Java. CPU | by Engineering Digest | Medium
2. run( ): The entry point for the thread. When the thread is started, the run()
method is invoked. If the thread was created using a class that implements
Runnable , the run() method will execute the run() method of that Runnable
object.
4. join( ): Waits for this thread to die. When one thread calls the join() method of
another thread, it pauses the execution of the current thread until the thread
being joined has completed its execution.
@Override
public void run() {
System.out.println("Thread is Running...");
for (int i = 1; i <= 5; i++) {
for (int j = 0; j < 5; j++) {
System.out.println(Thread.currentThread().getName() + " - Prior
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
https://engineeringdigest.medium.com/multithreading-in-java-39f34724bbf6 8/33
08/02/2025, 11:21 Multithreading in Java. CPU | by Engineering Digest | Medium
n.start();
}
}
https://engineeringdigest.medium.com/multithreading-in-java-39f34724bbf6 9/33
08/02/2025, 11:21 Multithreading in Java. CPU | by Engineering Digest | Medium
public static void main(String[] args) {
MyThread myThread = new MyThread();
myThread.setDaemon(true); // myThread is daemon thread ( like Garbage c
MyThread t1 = new MyThread();
t1.start(); // t1 is user thread
myThread.start();
System.out.println("Main Done");
}
}
Synchronisation
Let’s see an example where two threads are incrementing same couter.
class Counter {
private int count = 0; // shared resource
@Override
public void run() {
for (int i = 0; i < 1000; i++) {
counter.increment();
}
}
https://engineeringdigest.medium.com/multithreading-in-java-39f34724bbf6 10/33
08/02/2025, 11:21 Multithreading in Java. CPU | by Engineering Digest | Medium
}catch (Exception e){
}
System.out.println(counter.getCount()); // Expected: 2000, Actual will
}
}
The output of the code is not 2000 because the increment method in the Counter
class is not synchronized. This results in a race condition when both threads try to
increment the count variable concurrently.
Without synchronization, one thread might read the value of count before the other
thread has finished writing its incremented value. This can lead to both threads
reading the same value, incrementing it, and writing it back, effectively losing one
of the increments.
class Counter {
private int count = 0; // shared resource
By synchronizing the increment method, you ensure that only one thread can
execute this method at a time, which prevents the race condition. With this change,
the output will consistently be 2000.
Locks
The synchronized keyword in Java provides basic thread-safety but has limitations: it
locks the entire method or block, leading to potential performance issues. It lacks a
try-lock mechanism, causing threads to block indefinitely, increasing the risk of
deadlocks. Additionally, synchronized doesn't support multiple condition variables,
https://engineeringdigest.medium.com/multithreading-in-java-39f34724bbf6 11/33
08/02/2025, 11:21 Multithreading in Java. CPU | by Engineering Digest | Medium
offering only a single monitor per object with basic wait/notify mechanisms. In
contrast, explicit locks ( Lock interface) offer finer-grained control, try-lock
capabilities to avoid blocking, and more sophisticated thread coordination through
multiple condition variables, making them more flexible and powerful for complex
concurrency scenarios.
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
Reentrant Lock
A Reentrant Lock in Java is a type of lock that allows a thread to acquire the same
lock multiple times without causing a deadlock. If a thread already holds the lock, it
can re-enter the lock without being blocked. This is useful when a thread needs to
repeatedly enter synchronized blocks or methods within the same execution flow.
The ReentrantLock class from the java.util.concurrent.locks package provides this
functionality, offering more flexibility than the synchronized keyword, including
try-locking, timed locking, and multiple condition variables for advanced thread
coordination.
https://engineeringdigest.medium.com/multithreading-in-java-39f34724bbf6 13/33
08/02/2025, 11:21 Multithreading in Java. CPU | by Engineering Digest | Medium
example.outerMethod();
}
}
Methods of ReentrantLock
lock()
Acquires the lock, blocking the current thread until the lock is available. It
would block the thread until the lock becomes available, potentially leading to
situations where a thread waits indefinitely.
If the lock is already held by another thread, the current thread will wait until it
can acquire the lock.
tryLock()
Tries to acquire the lock without waiting. Returns true if the lock was acquired,
false otherwise.
This is non-blocking, meaning the thread will not wait if the lock is not available.
Attempts to acquire the lock, but with a timeout. If the lock is not available, the
thread waits for the specified time before giving up. It is used when you want to
attempt to acquire the lock without waiting indefinitely. It allows the thread to
proceed with other work if the lock isn't available within the specified time. This
approach is useful to avoid deadlock scenarios and when you don't want a thread
to block forever waiting for a lock.
Returns true if the lock was acquired within the timeout, false otherwise.
unlock()
Must be called in a finally block to ensure that the lock is always released even
if an exception occurs.
lockInterruptibly()
https://engineeringdigest.medium.com/multithreading-in-java-39f34724bbf6 14/33
08/02/2025, 11:21 Multithreading in Java. CPU | by Engineering Digest | Medium
Acquires the lock unless the current thread is interrupted. This is useful when
you want to handle interruptions while acquiring a lock.
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
https://engineeringdigest.medium.com/multithreading-in-java-39f34724bbf6 15/33
08/02/2025, 11:21 Multithreading in Java. CPU | by Engineering Digest | Medium
writerThread.start();
readerThread1.start();
readerThread2.start();
writerThread.join();
readerThread1.join();
readerThread2.join();
Fairness of Locks
Fairness in the context of locks refers to the order in which threads acquire a lock. A
fair lock ensures that threads acquire the lock in the order they requested it,
preventing thread starvation. With a fair lock, if multiple threads are waiting, the
longest-waiting thread is granted the lock next. However, fairness can lead to lower
throughput due to the overhead of maintaining the order. Non-fair locks, in
contrast, allow threads to “cut in line,” potentially offering better performance but
at the risk of some threads waiting indefinitely if others frequently acquire the lock.
https://engineeringdigest.medium.com/multithreading-in-java-39f34724bbf6 16/33
08/02/2025, 11:21 Multithreading in Java. CPU | by Engineering Digest | Medium
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
thread1.start();
thread2.start();
thread3.start();
}
}
Deadlock
A deadlock occurs in concurrent programming when two or more threads are
blocked forever, each waiting for the other to release a resource. This typically
happens when threads hold locks on resources and request additional locks held by
other threads. For example, Thread A holds Lock 1 and waits for Lock 2, while
Thread B holds Lock 2 and waits for Lock 1. Since neither thread can proceed, they
remain stuck in a deadlock state. Deadlocks can severely impact system
https://engineeringdigest.medium.com/multithreading-in-java-39f34724bbf6 17/33
08/02/2025, 11:21 Multithreading in Java. CPU | by Engineering Digest | Medium
class Pen {
public synchronized void writeWithPenAndPaper(Paper paper) {
System.out.println(Thread.currentThread().getName() + " is using pen "
paper.finishWriting();
}
class Paper {
public synchronized void writeWithPaperAndPen(Pen pen) {
System.out.println(Thread.currentThread().getName() + " is using paper
pen.finishWriting();
}
@Override
public void run() {
pen.writeWithPenAndPaper(paper); // thread1 locks pen and tries to lock
}
}
@Override
https://engineeringdigest.medium.com/multithreading-in-java-39f34724bbf6 18/33
08/02/2025, 11:21 Multithreading in Java. CPU | by Engineering Digest | Medium
public void run() {
synchronized (pen){
paper.writeWithPaperAndPen(pen); // thread2 locks paper and tries t
}
}
}
thread1.start();
thread2.start();
}
}
Thread communication
class SharedResource {
private int data;
private boolean hasData;
@Override
public void run() {
for (int i = 0; i < 10; i++) {
resource.produce(i);
}
}
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
int value = resource.consume();
}
}
}
producerThread.start();
consumerThread.start();
}
}
Executors framework
https://engineeringdigest.medium.com/multithreading-in-java-39f34724bbf6 20/33
08/02/2025, 11:21 Multithreading in Java. CPU | by Engineering Digest | Medium
It will help in
2. Resource management
3. Scalability
4. Thread reuse
5. Error handling
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
}
executor.shutdown();
// executor.shutdown();
try {
executor.awaitTermination(1, TimeUnit.SECONDS);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
https://engineeringdigest.medium.com/multithreading-in-java-39f34724bbf6 21/33
08/02/2025, 11:21 Multithreading in Java. CPU | by Engineering Digest | Medium
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
long result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
return result;
}
}
Future
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
Hello
null
Task is done !
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
https://engineeringdigest.medium.com/multithreading-in-java-39f34724bbf6 22/33
08/02/2025, 11:21 Multithreading in Java. CPU | by Engineering Digest | Medium
public class Main {
Hello
Task is done !
Atomic classes
Volatile keyword
class SharedObj {
private volatile boolean flag = false;
writerThread.start();
readerThread.start();
}
}
CountDownLatch
https://engineeringdigest.medium.com/multithreading-in-java-39f34724bbf6 24/33
08/02/2025, 11:21 Multithreading in Java. CPU | by Engineering Digest | Medium
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
Cyclic Barrier
https://engineeringdigest.medium.com/multithreading-in-java-39f34724bbf6 25/33
08/02/2025, 11:21 Multithreading in Java. CPU | by Engineering Digest | Medium
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
webServerThread.start();
databaseThread.start();
cacheThread.start();
messagingServiceThread.start();
@Override
public void run() {
try {
System.out.println(name + " initialization started.");
Thread.sleep(initializationTime); // Simulate time taken to initial
System.out.println(name + " initialization complete.");
barrier.await();
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}
https://engineeringdigest.medium.com/multithreading-in-java-39f34724bbf6 26/33
08/02/2025, 11:21 Multithreading in Java. CPU | by Engineering Digest | Medium
}
}
Follow
Responses (11)
Respond
R Shah
Nov 17, 2024
Process
A process is the active execution of that program. It includes the program's code, a program counter (to
track the current instruction), memory allocation, and system resources.
14 Reply
https://engineeringdigest.medium.com/multithreading-in-java-39f34724bbf6 27/33
08/02/2025, 11:21 Multithreading in Java. CPU | by Engineering Digest | Medium
Nandkishor Patil
Aug 20, 2024
Awesome as always
5 Reply
Aprajitachhawi
Aug 15, 2024
3 Reply
Engineering Digest
Generics
Without Generics
https://engineeringdigest.medium.com/multithreading-in-java-39f34724bbf6 28/33
08/02/2025, 11:21 Multithreading in Java. CPU | by Engineering Digest | Medium
Engineering Digest
What is a Database?
A database is an organized collection of structured information, or data, typically stored
electronically in a computer system. Databases…
Jan 6 6 2
https://engineeringdigest.medium.com/multithreading-in-java-39f34724bbf6 29/33
08/02/2025, 11:21 Multithreading in Java. CPU | by Engineering Digest | Medium
Jan 24 317 14
https://engineeringdigest.medium.com/multithreading-in-java-39f34724bbf6 30/33
08/02/2025, 11:21 Multithreading in Java. CPU | by Engineering Digest | Medium
Lists
Rabinarayan Patra
https://engineeringdigest.medium.com/multithreading-in-java-39f34724bbf6 31/33
08/02/2025, 11:21 Multithreading in Java. CPU | by Engineering Digest | Medium
Yash
Jan 28 294 5
https://engineeringdigest.medium.com/multithreading-in-java-39f34724bbf6 32/33
08/02/2025, 11:21 Multithreading in Java. CPU | by Engineering Digest | Medium
https://engineeringdigest.medium.com/multithreading-in-java-39f34724bbf6 33/33