0% found this document useful (0 votes)
5 views22 pages

Unit 4 Multithreading

The document explains the differences between multitasking and multithreading, highlighting that multitasking allows multiple processes to run concurrently while sharing resources, whereas multithreading involves multiple threads within a single process sharing the same memory. It details the life cycle of threads, their states, and how they can be created in Java using either the Thread class or the Runnable interface. Additionally, it discusses the advantages and disadvantages of both processes and threads, emphasizing the efficiency and responsiveness of multithreading in applications.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views22 pages

Unit 4 Multithreading

The document explains the differences between multitasking and multithreading, highlighting that multitasking allows multiple processes to run concurrently while sharing resources, whereas multithreading involves multiple threads within a single process sharing the same memory. It details the life cycle of threads, their states, and how they can be created in Java using either the Thread class or the Runnable interface. Additionally, it discusses the advantages and disadvantages of both processes and threads, emphasizing the efficiency and responsiveness of multithreading in applications.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 22

Unit-4 Multithreading

Difference between Multi-tasking and Multi-threading

What is Multitasking?
Multi-tasking is the ability of an operating system to run multiple processes or tasks
concurrently, sharing the same processor and other resources.

In multitasking, the operating system divides the CPU time between multiple tasks,
allowing them to execute simultaneously.

Each task is assigned a time slice, or a portion of CPU time, during which it can
execute its code.

Multi-tasking is essential for increasing system efficiency, improving user


productivity, and achieving optimal resource utilization.

Multitasking is when a CPU is provided to execute multiple tasks at a time.

Multitasking involves often CPU switching between tasks so that users can
collaborate with each program together.

In multitasking, the processes share separate memory and resources.

Multitasking involves CPU switching between tasks rapidly, So little time is needed in
order to switch from one user to the next.

What is Multithreading?

Multithreading is a system in which many threads are created from a process through which
the computer power is increased. In multithreading,

CPU is provided in order to execute many threads from a process at a time, and in
multithreading, process creation is performed according to cost.

Unlike multitasking, multithreading provides the same memory and resources to the
processes for execution.
Multitasking Multithreading

While in multithreading, many threads are


In multitasking, users are allowed to
created from a process through which
perform many tasks by CPU.
computer power is increased.

Multitasking involves often While in multithreading also, CPU switching is


CPU switching between the tasks. often involved between the threads.

In multitasking, the processes share While in multithreading, processes are


separate memory. allocated the same memory.

The multitasking component While the multithreading component does not


involves multiprocessing. involve multiprocessing.

While in multithreading also, a CPU is


In multitasking, the CPU is provided in
provided in order to execute many threads
order to execute many tasks at a time.
from a process at a time.

In multitasking, processes don't share


While in multithreading, each process shares
the same resources, each process is
the same resources.
allocated separate resources.

Multitasking is slow compared to


While multithreading is faster.
multithreading.

In multitasking, termination of a process While in multithreading, termination of thread


takes more time. takes less time.

Isolation and memory protection exist in Isolation and memory protection does not
Multitasking Multithreading

multitasking. exist in multithreading.

It helps in developing efficient operating


It helps in developing efficient programs.
systems.

Involves dividing a single process into multiple


Involves running multiple independent
threads that can execute concurrently
processes or tasks

Multiple processes or tasks run Multiple threads within a single process share
simultaneously, sharing the same the same memory space and resources
processor and resources

Threads share the same memory space and


Each process or task has its own
resources of the parent process
memory space and resources

Used to manage multiple processes and Used to manage multiple processes and
improve system efficiency improve system efficiency

Examples: running multiple applications Examples: splitting a video encoding task into
on a computer, running multiple servers multiple threads, implementing a responsive
on a network user interface in an application

Java Threads

Java threads are lightweight sub -processes, representing the smallest unit of execution
with separate paths. The main advantage of multiple threads is efficiency (allowing
multiple things at the same time).

For example, in MS Word, one thread automatically formats the document while another
thread is taking user input. Additionally, multithreading ensures quick response, as other
threads can continue execution even if one gets stuck, keeping the application responsive.
As shown in the above diagram, a thread runs inside the process, and there will be
context-based switching between threads.

There can be multiple processes running in an OS, and each process can have multiple
threads running simultaneously.

The Multithreading concept is popularly applied in games, animation, etc.

Concept of Multitasking
This Multitasking can be enabled in two ways:
1. Process-Based Multitasking
2. Thread-Based Multitasking

1. Process-Based Multitasking (Multiprocessing): In this type of multitasking,


processes are heavyweight, and each process is allocated by a separate memory
area and as the process is heavyweight the cost of communication between
processes is high and it takes a long time for switching between processes as it
involves actions such as loading, saving in registers, updating maps, lists, etc.

2. Thread-Based Multitasking: As we discussed above, threads are


Provided with lightweight nature and share the same address space, and the cost of
communication between threads is also low.

What is Process?
Processes are basically the programs that are dispatched from the ready state and are
scheduled in the CPU for execution.

PCB ( Process Control Block ) holds the context of process. A process can create other
processes which are known as Child Processes.

The process takes more time to terminate, and it is isolated means it does not share the
memory with any other process.

The process can have the following states new, ready, running, waiting, terminated and
suspended.

What is Thread?
Threads are often called "lightweight processes" because they share some features of
processes but are smaller and faster.
Each thread is always part of one specific process. A thread has three states: Running,
Ready and Blocked.

A thread takes less time to terminate as compared to the process but unlike the process,
threads do not isolate.

Examples:
 Imagine a word processor that works with two separate tasks happening at the same
time. One task focuses on interacting with the user, like responding to typing or scrolling,
while the other works in the background to adjust the formatting of the entire document.

For example if you delete a sentence on page 1, the user-focused task immediately tells
the background task to reformat the entire book. While the background task is busy
reformatting, the user-focused task continues to handle simple actions like letting you
scroll through page 1 or click on things.
 When you use a web browser, threads are working behind the scenes to handle different
tasks simultaneously.

For example:
One thread is loading the webpage content (text, images, videos).

Another thread is responding to your actions like scrolling, clicking, or typing.


A separate thread might be running JavaScript to make the webpage interactive.
This multitasking makes the browser smooth and responsive.

For instance you can scroll through a page or type in a search bar while the rest of the
page is still loading. If threads weren’t used the browser would freeze and wait for one
task to finish before starting another. Threads ensure everything feels fast and seamless.

Life Cycle of Thread : During its lifetime, a thread transitions through several states,
they are:
1. New State
2. Active State
3. Waiting/Blocked State
4. Timed Waiting State
5. Terminated State
Working of Thread States:
1.New State: By default, a thread will be in a new state, in this state, code has not yet
started execution.

2. Active State: A thread that is a new state by default gets transferred to Active
state when it invokes the start() method, this Active state contains two sub-states namely:

 Runnable State: In this state, The thread is ready to run at any given time and it's the
job of the Thread Scheduler to provide the thread time for the runnable state preserved
threads. A program that has obtained Multithreading shares slices of time intervals which
are shared between threads hence, these threads run for some short span of time and
wait in the runnable state to get their schedules slice of a time interval.

 Running State: When the thread receives CPU allocated by thread scheduler, it
transfers from the "Runnable" state to the "Running" state, and after the expiry of its
given time slice session, it again moves back to the "Runnable" state and waits for its
next time slice.

3. Waiting/Blocked State:

If a thread is inactive but on a temporary time, then either it is a waiting or blocked state, for
example, if there are two threads, T1 and T2 where T1 needs to communicate to the
camera and the other thread T2 already using a camera to scan then T1 waits until T2
thread completes its work, at this state T1 is parked in waiting for the state, and in another
scenario, the user called two Threads T2 and T3 with the same functionality and both had
same time slice given by thread scheduler then both Threads T1, T2 is in a blocked state.
When there are multiple threads parked in a Blocked/Waiting state thread scheduler clears
queue by rejecting unwanted threads and allocating CPU on a priority basis.

4. Timed Waiting State:

Sometimes the longer duration of waiting for threads causes starvation, if we take an
example like there are two threads T1, T2 waiting for CPU and T1 is undergoing a critical
coding operation and if it does not exist the CPU until its operation gets executed then T2
will be exposed to longer waiting with undetermined certainty, In order to avoid this
starvation situation, we had timed waiting for the state to avoid that kind of scenario as in
timed waiting, each thread has a time period for which sleep() method is invoked and after
the time expires the threads starts executing its task.

5. Terminated State:
A thread will be in terminated state, due to the below reasons:
1. Termination is achieved by a thread when it finishes its task normally.
2. Sometimes threads may be terminated due to unusual events like segmentation
faults, exceptions...etc. and such kind of termination can be called abnormal
termination.
3. A terminated thread means it is dead and no longer available.

Process Thread

Process means a program in


Thread means a segment of a process.
execution.

A process takes more time to


A thread takes less time to terminate.
terminate.

It takes more time for creation. It takes less time for creation.

It also takes more time for context


It takes less time for context switching.
switching.

A process is less efficient in terms


Thread is more efficient in terms of communication.
of communication.

Multiprogramming holds the We don't need multi programs in action for multiple threads
concepts of multi-process. because a single process consists of multiple threads.

Every process runs in its own


Threads share memory.
memory.

A process is heavyweight A Thread is lightweight as each thread in a process shares


compared to a thread. code, data, and resources.

Process switching uses an Thread switching may not require calling involvement of
interface in an operating system. operating system.
Process Thread

If one process is blocked, then it


If a user-level thread is blocked, then all other user-level
will not affect the execution of
threads are blocked.
other processes.

A process has its own Process


Thread has Parents' PCB, its own Thread Control Block,
Control Block, Stack, and Address
and Stack and common Address space.
Space.

Since all threads of the same process share address space


Changes to the parent process do
and other resources so any changes to the main thread may
not affect child processes.
affect the behavior of the other threads of the process.

A system call is involved in it. No system call is involved, it is created using APIs.

A process does not share data with


Threads share data with each other.
each other.

Advantages of Process
 Processes work independently in their own memory, ensuring no interference and better
security.
 Resources like CPU and memory are allocated effectively to optimize performance.
 Processes can be prioritized to ensure important tasks get the resources they need.
Disadvantages of Process
 Frequent switching between processes can slow down the system and reduce speed.
 Improper resource management can cause deadlocks where processes stop working
and block progress.
 Having too many processes can make the process table take up a lot of memory. This
can also make searching or updating the table slower, which can reduce system
performance.

Advantages of Thread
 When there is a lot of computing and input/output (I/O) work, threads help tasks run at
the same time, making the app faster.
 Another advantage for having threads is that since they are lighter weight than
processes, they are easier (i.e., faster) to create and destroy than processes.
 Many apps need to handle different tasks at the same time. For example, a web browser
can load a webpage, play a video, and let you scroll all at once. Threads make this
possible by dividing these tasks into smaller parts that can run together.
Disadvantages of Thread
 Threads in the same process are not completely independent like separate processes.
They share the same memory space including global variables. This means one thread
can accidentally change or even erase another thread’s data as there is no protection
between them.
 Threads also share resources like files. For example - if one thread closes a file while
another is still using it, it can cause errors or unexpected behavior.
 If too many threads are created they can slow down the system or cause it to run out of
memory.
Java Main Thread

As we are familiar, we create main method in each and every Java program, which acts as
an entry point for the code to get executed by JVM, Similarly in this multithreading concept,
each program has one main thread which was provided by default by JVM, hence whenever
a program is being created in java, JVM provides the main thread for its execution.

When a Java program starts up, one thread begins running immediately. This is usually
called the main thread of our program because it is the one that is executed when our
program begins.

There are certain properties associated with the main thread which are as follows:
 It is the thread from which other “child” threads will be spawned.
 Often, it must be the last thread to finish execution because it performs various shutdown
actions

How to control Main thread


The main thread is created automatically when our program is started. To control it we must
obtain a reference to it. This can be done by calling the method currentThread( ) which is
present in Thread class. This method returns a reference to the thread on which it is called.
The default priority of Main thread is 5 and for all remaining user threads priority will be
inherited from parent to child.
public class Thread_Demo extends Thread

public void run()

System.out.println("when start() is invoked run() is automatically called");

public static void main(String[] args)

Thread_Demo th=new Thread_Demo();

Thread t1=new Thread("My Thread");

System.out.println("before calling start() a thread is already running i.e. main thread\t"


+Thread.currentThread());

t1.start();

System.out.println("newly created thread ==="+t1.getName());

}}

How to Create Threads in Java?

We can create threads in java using two ways, namely :


 Extending Thread Class
 Implementing a Runnable interface
1. By Extending Thread Class
We can run threads in Java by using thread class, which provides constructors and methods
for creating and performing operations on a thread, which extends a thread class that can
implement runnable interface.
public class Thread_Demo extends Thread

public void run()

System.out.println("when start() is invoked run() is automatically called");

public static void main(String[] args)

Thread_Demo th=new Thread_Demo();

Thread t1=new Thread("My Thread");

System.out.println("before calling start() a thread is already running i.e. main thread\t"


+Thread.currentThread());

t1.start();

System.out.println("newly created thread ==="+t1.getName());

}}

2. Using Runnable Interface


public class RunnableInterface implements Runnable

public void run()

System.out.println("Threaad is executing");

public static void main(String[] aaa)

RunnableInterface r=new RunnableInterface();

System.out.println(Thread.currentThread());

Thread th=new Thread(r);

th.start();

System.out.println(th.isAlive());

try

{
for(int i=0;i<4;i++)

System.out.println(i);

th.sleep(1000);

System.out.println(th.isAlive());

}catch(Exception ee)

System.out.println(ee);

} } }

Sleep() : The sleep() method in Java is a static method of the Thread class used to pause the
execution of the current thread for a specified period. It is commonly used for introducing
delays, controlling the pace of execution, or simulating real-time behavior in multithreaded
applications.
class SleepExample {
public static void main(String[] args) {
try {
System.out.println("Thread is going to sleep.");
Thread.sleep(2000); // Sleep for 2 seconds
System.out.println("Thread woke up.");
} catch (InterruptedException e) {
System.out.println("Thread was interrupted while sleeping.");
}
}
}

join():
java.lang.Thread class provides the join() method which allows one thread to wait until
another thread completes its execution. If t is a Thread object whose thread is currently
executing, then t.join() will make sure that t is terminated before the next instruction is
executed by the program.

If there are multiple threads calling the join () methods that means overloading on join
allows the programmer to specify a waiting period.

However, as with sleep, join is dependent on the OS for timing, so you should not assume
that join will wait exactly as long as you specify. There are three overloaded join functions.

class Priority_Demo extends Thread


{

public synchronized void run()


{
System.out.println(Thread.currentThread());

for(int i=0;i<=5;i++)
{
try
{
Thread.sleep(700);
System.out.println(i);
}catch(Exception ee){}
}

}
public static void main(String[] aa)
{
Priority_Demo pd1=new Priority_Demo();
Priority_Demo pd2=new Priority_Demo();
Priority_Demo pd3=new Priority_Demo();

pd1.start();
try
{
pd1.join();
}catch(Exception e){}
//pd2.setPriority(Thread.MIN_PRIORITY);
pd2.start();

try
{
pd2.join();
}catch(Exception e){}

//pd3.setPriority(Thread.MAX_PRIORITY);
pd3.start();
try
{
pd3.join();
}catch(Exception e){}

}
}

Synchronization : Synchronization in Java is a mechanism that controls the access of


multiple threads to shared resources, preventing data corruption and race conditions. It
ensures that only one thread can access a critical section of code or a shared resource at a
time.

Key Concepts:
 Shared Resources: Data or objects accessed by multiple threads.
 Critical Section: A block of code that accesses shared resources and needs to be protected
from concurrent access.
 Race Condition: A situation where multiple threads access and modify shared data
concurrently, leading to unpredictable and incorrect results.
 Need of Synchronization:
 When multiple threads share resources, synchronization make sure that only one
thread accesses the resource at a time. This prevents problem like data getting mixed
up or broken because of multiple threads changing it together.

class Account

synchronized public void getBalance()

for (int i = 0; i < 3; i++)

System.out.println(i);

try

Thread.sleep(100);

catch (Exception e)

System.out.println(e);

class Balance extends Thread

Account ac;

Balance(Account ac)

{
this.ac = ac;

public void run()

ac.getBalance();

public class Synchronized_Demo

public static void main(String[] args)

Account obj = new Account();

Balance t1 = new Balance(obj);

Balance t2 = new Balance(obj);

t1.start();

t2.start();

Synchronized Blocks in Java


Java provides a way to create threads and synchronise their tasks using synchronized
blocks.
A synchronized block in Java is synchronized on some object. Synchronized blocks in
Java are marked with the synchronized keyword. All synchronized blocks synchronize on
the same object and can only have one thread executed inside them at a time. All other
threads attempting to enter the synchronized block are blocked until the thread inside the
synchronized block exits the block. If you want to master concurrency and understand how
to avoid common pitfalls,

General Form of Synchronized Block


synchronized(sync_object)
{
// Access shared variables and other
// shared resources
}
This synchronization is implemented in Java with a concept called monitors or locks. Only
one thread can own a monitor at a given time. When a thread acquires a lock, it is said to
have entered the monitor. All other threads attempting to enter the locked monitor will be
suspended until the first thread exits the monitor.

class Counter {

private int c = 0; // Shared variable

// Method with synchronization block

public void inc() {

synchronized(this) { // Synchronize only this block

c++;

// Method to get counter value

public int get() {

return c;

public class SynchronizedBlock {

public static void main(String[] args) {

Counter cnt = new Counter(); // Shared resource

// Thread 1 to increment counter

Thread t1 = new Thread(() -> {

for (int i = 0; i < 1000; i++) {

cnt.inc();
}

});

// Thread 2 to increment counter

Thread t2 = new Thread(() -> {

for (int i = 0; i < 1000; i++) {

cnt.inc();

});

// Start both threads

t1.start();

t2.start();

// Wait for threads to finish

try {

t1.join();

t2.join();

} catch (InterruptedException e) {

e.printStackTrace();

// Print final counter value

System.out.println("Counter: " + cnt.get());

Daemon Thread in Java

A Daemon thread is created to support the user threads. It generallty works in background
and terminated once all the other threads are closed. Garbage collector is one of the
example of Daemon thread.
Characteristics of a Daemon Thread in Java
 A Daemon thread is a low priority thread.
 A Daemon thread is a service provider thread and should not be used as user thread.
 JVM automatically closes the daemon thread(s) if no active thread is present and revives it if
user threads are active again.
 A daemon thread cannot prevent JVM to exit if all user threads are done.
class Daemon_Thread extends Thread

public static void main(String[] aa)

Thread t1=new Thread("Thread One");

Thread t2=new Thread("Thread Two");

t1.start();

t2.setDaemon(true);

System.out.println(t1.isDaemon());

t2.start();

System.out.println(t2.isDaemon());

public void run()

System.out.println("run() is invoked automatically");

Priorities in Threads
Priorities in Threads in Java is a concept where each thread has a priority in layman’s
language one can say every object has priority here which is represented by numbers
ranging from 1 to 10, and the constant defined can help to implement which are mentioned
below.

Constant Description

public static int NORM_PRIORITY Sets the default priority for the Thread. (Priority: 5)
Constant Description

public static int MIN_PRIORITY Sets the Minimum Priority for the Thread. (Priority: 1)

public static int MAX_PRIORITY Sets the Maximum Priority for the Thread. (Priority: 10)

class Priority_Demo extends Thread

public synchronized void run()

System.out.println(Thread.currentThread());

for(int i=0;i<=5;i++)

try

Thread.sleep(700);

System.out.println(i);

}catch(Exception ee){}

public static void main(String[] aa)

Priority_Demo pd1=new Priority_Demo();

Priority_Demo pd2=new Priority_Demo();

Priority_Demo pd3=new Priority_Demo();

pd1.start();

try
{

pd1.join();

}catch(Exception e){}

//pd2.setPriority(Thread.MIN_PRIORITY);

pd2.start();

try

pd2.join();

}catch(Exception e){}

//pd3.setPriority(Thread.MAX_PRIORITY);

pd3.start();

try

pd3.join();

}catch(Exception e){}

Inter-thread Communication in Java


Inter-thread communication is important when you develop an application where two or
more threads exchange some information. Inter-thread communication is achieved by using
the wait(), notify(), and notifyAll() methods of the Object class.
Methods used for Inter-thread Communication
There are three simple methods and a little trick which makes thread communication possible. All the three
methods are listed below −

1. public void wait():Causes the current thread to wait until another thread invokes the notify().

2. public void notify():Wakes up a single thread that is waiting on this object's monitor.

3. public void notifyAll():Wakes up all the threads that called wait( ) on the same object.
import java.io.*;

import java.util.*;

class myThread extends Thread

int sum = 0;

public void run()

synchronized (this)

System.out.println("child thread start calculation");

for (int i = 0; i <= 10; i++)

sum += i;

System.out.println("child thread trying to give notification");

this.notify();

// Class 2

class WaitAndNotify

public static void main(String[] args) throws InterruptedException

myThread t1 = new myThread();

t1.start();

synchronized (t1)

System.out.println("main thread trying to call wait method");

t1.wait();
System.out.println("main thread get notify");

System.out.println(t1.sum);

You might also like