SlideShare a Scribd company logo
Synchronization
• When two or more threads need access to a shared
resource, they need some way to ensure that the resource
will be used by only one thread at a time. The process by
which this is achieved is called synchronization.
• Java provides unique, language-level support for it. Key to
synchronization is the concept of the monitor (also called a
semaphore).
• A monitor is an object that is used as a mutually exclusive
lock, or mutex. 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. These other threads are said to be
waiting for the monitor. A thread that owns a monitor can
reenter the same monitor if it so desires.
• We can synchronize our code in either of two ways. Both
involve the use of the synchronized keyword, and both are
examined here.
• Using synchronized Methods
• The synchronized Statement
• synchronized Methods : All objects have their own implicit
monitor associated with them. To enter an object’s monitor,
just call a method that has been modified with the
synchronized keyword. While a thread is inside a synchronized
method, all other threads that try to call it (or any other
synchronized method) on the same instance have to wait. To
exit the monitor and relinquish control of the object to the
next waiting thread, the owner of the monitor simply returns
from the synchronized method.
class callme{
static int i=1;
//synchronized
static void print() {
System.out.print("( HI ");
try { Thread.sleep(1000);
}
catch(InterruptedException e) { System.out.println("Interrupted");
}
System.out.println(i+" )");
i++;
} }
class A extends Thread {
public void run() {
for(int i=1;i<=5;i++)
callme.print();
} }
class B extends Thread{
public void run() {
for(int i=1;i<=5;i++)
callme.print();
}
}
class test {
public static void main(String args[])
{
A th1= new A();
th1.start(); // new A().start();
B th2=new B();
th2.start();
}
}
( HI ( HI 1 )
1 )
( HI ( HI 3 )
( HI 3 )
( HI 5 )
( HI 5 )
( HI 7 )
( HI 7 )
( HI 9 )
9 )
• Here the value of variable i is updated in unordered way by both
the threads A and B. The output may change for each run. This can
lead to a series problem if i is some important shared data or a
control flag. The output printing is also not in order. To solve the
problem we need synchronization over the print() method.
• If the print() method is defined as:
synchronized static void print(){---------}
• Then the method is synchronized and the output will be->
( HI 1 )
( HI 2 )
( HI 3 )
( HI 4 )
( HI 5 )
( HI 6 )
( HI 7 )
( HI 8 )
( HI 9 )
( HI 10 )
• Also the output will remain same for each run.(As only one thread can
execute the print() method at a time and other thread has to wait for
completion of current call to print method.)
• The synchronized Statement: While creating synchronized methods
within classes that you create is an easy and effective means of achieving
synchronization, it will not work in all cases.
• Consider the following. Imagine that we want to synchronize access to
objects of a class that was not designed for multithreaded access. That is,
the class does not use synchronized methods. Further, this class was not
created by us, but by a third party, and we do not have access to the
source code. Thus, we can’t add synchronized to the appropriate methods
within the class. How can access to an object of this class be
synchronized?
• The solution to this problem is quite easy: simply put calls to the methods
defined by this class inside a synchronized block.
synchronized(object) {
// statements to be synchronized
}
• Here, object is a reference to the object being synchronized. A synchronized
block ensures that a call to a method that is a member of object occurs
only after the current thread has successfully entered object’s monitor.
class callme{
int i=1; //non-static member
void print() { //non-static member
System.out.print("( HI ");
try { Thread.sleep(1000); }
catch(InterruptedException e) { System.out.println("Interrupted"); }
System.out.println(i+" )");
i++;
} }
class A extends Thread {
callme obj;
A(callme target) { obj=target; }
public void run() {
for(int i=1;i<=5;i++) {
synchronized(obj)
{ obj.print(); } }
} }
class B extends Thread{
callme obj;
B(callme target){ obj=target; }
public void run() {
for(int i=1;i<=5;i++)
{ synchronized(obj)
{obj.print(); } }
} }
class test {
public static void main(String args[]) {
callme obj1=new callme();
A th1= new A(obj1);
th1.start(); // new A().start();
B th2=new B(obj1);
th2.start();
}
}
• Here both thread are referring to the same instance/object of class
callme. The call to method print() is in synchronized block this time.
( HI 1 )
( HI 2 )
( HI 3 )
( HI 4 )
……..
( HI 9 )
( HI 10 )
So here without changing the original class callme the call to print
method is executed in synchronized block. This will have the same
effect as the previous case.(Where the print method is ynchronized.)
Interthread Communication
• Polling is usually implemented by a loop that is used to
check some condition repeatedly. Once the condition is
true, appropriate action is taken. This wastes CPU time.
• To avoid polling, Java includes an elegant interprocess
communication mechanism via the wait( ), notify( ), and
notifyAll( ) methods. These methods are implemented as
final methods in Object, so all classes have them. All three
methods can be called only from within a synchronized
context.
• wait( ) tells the calling thread to give up the monitor and go
to sleep until some other thread enters the same monitor
and calls notify( ).
• notify( ) wakes up the first thread that called wait( ) on the
same object.
• notifyAll( ) wakes up all the threads that called wait( ) on
the same object. The highest priority thread will run first.
• These methods are declared within Object, as
shown here:
final void wait( ) throws InterruptedException
final void notify( )
final void notifyAll( )
class A {
public static void main(String[]args)throws InterruptedException {
B b =new B();
b.start();
synchronized(b) //thread got lock
{
System.out.println("Calling wait method");
b.wait();
System.out.println("Got notification"); }
System.out.println(b.total);
} }
class B extends Thread{
int total=0;
public void run() {
synchronized (this) //.thread got lock
{
System.out.println("Starting calculation");
for(int i=0;i<=1000;i++) { total=total+I; }
System.out.println("Giving notification call");
notify(); //thread releases lock again }} }
Calling wait method
Starting calculation
Giving notification call
Got notification
500500

More Related Content

What's hot (20)

Learning Java 3 – Threads and Synchronization
Learning Java 3 – Threads and SynchronizationLearning Java 3 – Threads and Synchronization
Learning Java 3 – Threads and Synchronization
caswenson
 
Multithreading Concepts
Multithreading ConceptsMultithreading Concepts
Multithreading Concepts
Arvind Krishnaa
 
Multithreading in Java
Multithreading in JavaMultithreading in Java
Multithreading in Java
Appsterdam Milan
 
Life cycle-of-a-thread
Life cycle-of-a-threadLife cycle-of-a-thread
Life cycle-of-a-thread
javaicon
 
Developing Multithreaded Applications
Developing Multithreaded ApplicationsDeveloping Multithreaded Applications
Developing Multithreaded Applications
Bharat17485
 
Java Thread Synchronization
Java Thread SynchronizationJava Thread Synchronization
Java Thread Synchronization
Benj Del Mundo
 
Threading in C#
Threading in C#Threading in C#
Threading in C#
Medhat Dawoud
 
12 multi-threading
12 multi-threading12 multi-threading
12 multi-threading
APU
 
Java Multithreading and Concurrency
Java Multithreading and ConcurrencyJava Multithreading and Concurrency
Java Multithreading and Concurrency
Rajesh Ananda Kumar
 
Multithreading
MultithreadingMultithreading
Multithreading
SanthiNivas
 
Advanced Introduction to Java Multi-Threading - Full (chok)
Advanced Introduction to Java Multi-Threading - Full (chok)Advanced Introduction to Java Multi-Threading - Full (chok)
Advanced Introduction to Java Multi-Threading - Full (chok)
choksheak
 
Threads c sharp
Threads c sharpThreads c sharp
Threads c sharp
Karthick Suresh
 
.NET: Thread Synchronization Constructs
.NET: Thread Synchronization Constructs.NET: Thread Synchronization Constructs
.NET: Thread Synchronization Constructs
Sasha Kravchuk
 
multi threading
multi threadingmulti threading
multi threading
Yaswanth Babu Gummadivelli
 
Java Multithreading
Java MultithreadingJava Multithreading
Java Multithreading
Rajkattamuri
 
Thread model of java
Thread model of javaThread model of java
Thread model of java
myrajendra
 
javathreads
javathreadsjavathreads
javathreads
Arjun Shanka
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
Arafat Hossan
 
Thread model in java
Thread model in javaThread model in java
Thread model in java
AmbigaMurugesan
 
Java thread
Java threadJava thread
Java thread
Arati Gadgil
 
Learning Java 3 – Threads and Synchronization
Learning Java 3 – Threads and SynchronizationLearning Java 3 – Threads and Synchronization
Learning Java 3 – Threads and Synchronization
caswenson
 
Life cycle-of-a-thread
Life cycle-of-a-threadLife cycle-of-a-thread
Life cycle-of-a-thread
javaicon
 
Developing Multithreaded Applications
Developing Multithreaded ApplicationsDeveloping Multithreaded Applications
Developing Multithreaded Applications
Bharat17485
 
Java Thread Synchronization
Java Thread SynchronizationJava Thread Synchronization
Java Thread Synchronization
Benj Del Mundo
 
12 multi-threading
12 multi-threading12 multi-threading
12 multi-threading
APU
 
Java Multithreading and Concurrency
Java Multithreading and ConcurrencyJava Multithreading and Concurrency
Java Multithreading and Concurrency
Rajesh Ananda Kumar
 
Advanced Introduction to Java Multi-Threading - Full (chok)
Advanced Introduction to Java Multi-Threading - Full (chok)Advanced Introduction to Java Multi-Threading - Full (chok)
Advanced Introduction to Java Multi-Threading - Full (chok)
choksheak
 
.NET: Thread Synchronization Constructs
.NET: Thread Synchronization Constructs.NET: Thread Synchronization Constructs
.NET: Thread Synchronization Constructs
Sasha Kravchuk
 
Java Multithreading
Java MultithreadingJava Multithreading
Java Multithreading
Rajkattamuri
 
Thread model of java
Thread model of javaThread model of java
Thread model of java
myrajendra
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
Arafat Hossan
 

Viewers also liked (20)

26 io -ii file handling
26  io -ii  file handling26  io -ii  file handling
26 io -ii file handling
Ravindra Rathore
 
Ch11 communication
Ch11  communicationCh11  communication
Ch11 communication
adrienne0901
 
Introduction of reflection
Introduction of reflection Introduction of reflection
Introduction of reflection
Ravindra Rathore
 
28 networking
28  networking28  networking
28 networking
Ravindra Rathore
 
21 multi threading - iii
21 multi threading - iii21 multi threading - iii
21 multi threading - iii
Ravindra Rathore
 
Lecture 5 phasor notations
Lecture 5 phasor notationsLecture 5 phasor notations
Lecture 5 phasor notations
Ravindra Rathore
 
Vlsi
VlsiVlsi
Vlsi
Rina Ahire
 
Fiber optics101
Fiber optics101Fiber optics101
Fiber optics101
admercano101
 
Spread spectrum
Spread spectrumSpread spectrum
Spread spectrum
Rina Ahire
 
16 exception handling - i
16 exception handling - i16 exception handling - i
16 exception handling - i
Ravindra Rathore
 
T com presentation (error correcting code)
T com presentation   (error correcting code)T com presentation   (error correcting code)
T com presentation (error correcting code)
Akshit Jain
 
Low noise amplifier csd
Low noise amplifier csdLow noise amplifier csd
Low noise amplifier csd
Rina Ahire
 
Digital Communication 2
Digital Communication 2Digital Communication 2
Digital Communication 2
admercano101
 
Line coding
Line codingLine coding
Line coding
Gagan Randhawa
 
Digital Communication 4
Digital Communication 4Digital Communication 4
Digital Communication 4
admercano101
 
Limits
LimitsLimits
Limits
admercano101
 
Trigonometry101
Trigonometry101Trigonometry101
Trigonometry101
admercano101
 
Analytic geometry lecture2
Analytic geometry lecture2Analytic geometry lecture2
Analytic geometry lecture2
admercano101
 
Data Communication 1
Data Communication 1Data Communication 1
Data Communication 1
admercano101
 
27 applet programming
27  applet programming27  applet programming
27 applet programming
Ravindra Rathore
 

Similar to 22 multi threading iv (20)

Inter thread communication &amp; runnable interface
Inter thread communication &amp; runnable interfaceInter thread communication &amp; runnable interface
Inter thread communication &amp; runnable interface
keval_thummar
 
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
nimbalkarvikram966
 
Multithreading Presentation
Multithreading PresentationMultithreading Presentation
Multithreading Presentation
Neeraj Kaushik
 
Thread syncronization
Thread syncronizationThread syncronization
Thread syncronization
priyabogra1
 
Multithreading
MultithreadingMultithreading
Multithreading
backdoor
 
Java programming PPT. .pptx
Java programming PPT.                 .pptxJava programming PPT.                 .pptx
Java programming PPT. .pptx
creativegamerz00
 
Oops
OopsOops
Oops
Somdatta Kumar
 
Multi-threaded Programming in JAVA
Multi-threaded Programming in JAVAMulti-threaded Programming in JAVA
Multi-threaded Programming in JAVA
Vikram Kalyani
 
advanced java ppt
advanced java pptadvanced java ppt
advanced java ppt
PreetiDixit22
 
More topics on Java
More topics on JavaMore topics on Java
More topics on Java
Ahmed Misbah
 
Inter Thread Communicationn.pptx
Inter Thread Communicationn.pptxInter Thread Communicationn.pptx
Inter Thread Communicationn.pptx
SelvakumarNSNS
 
unit3multithreadingppt-copy-180122162204.pptx
unit3multithreadingppt-copy-180122162204.pptxunit3multithreadingppt-copy-180122162204.pptx
unit3multithreadingppt-copy-180122162204.pptx
ArunPatrick2
 
unit3 Exception Handling multithreadingppt.pptx
unit3 Exception Handling multithreadingppt.pptxunit3 Exception Handling multithreadingppt.pptx
unit3 Exception Handling multithreadingppt.pptx
ArunPatrick2
 
Sync, async and multithreading
Sync, async and multithreadingSync, async and multithreading
Sync, async and multithreading
Tuan Chau
 
Threads in Java
Threads in JavaThreads in Java
Threads in Java
HarshaDokula
 
Multithreading.pptx
Multithreading.pptxMultithreading.pptx
Multithreading.pptx
ssuserfcae42
 
Multithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of threadMultithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of thread
Kartik Dube
 
Multithreading in java programming language.ppt
Multithreading in java programming language.pptMultithreading in java programming language.ppt
Multithreading in java programming language.ppt
AutoAuto9
 
Md09 multithreading
Md09 multithreadingMd09 multithreading
Md09 multithreading
Rakesh Madugula
 
this power point presentation is about concurrency and multithreading
this power point presentation is about concurrency and multithreadingthis power point presentation is about concurrency and multithreading
this power point presentation is about concurrency and multithreading
Betty333100
 
Inter thread communication &amp; runnable interface
Inter thread communication &amp; runnable interfaceInter thread communication &amp; runnable interface
Inter thread communication &amp; runnable interface
keval_thummar
 
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
nimbalkarvikram966
 
Multithreading Presentation
Multithreading PresentationMultithreading Presentation
Multithreading Presentation
Neeraj Kaushik
 
Thread syncronization
Thread syncronizationThread syncronization
Thread syncronization
priyabogra1
 
Multithreading
MultithreadingMultithreading
Multithreading
backdoor
 
Java programming PPT. .pptx
Java programming PPT.                 .pptxJava programming PPT.                 .pptx
Java programming PPT. .pptx
creativegamerz00
 
Multi-threaded Programming in JAVA
Multi-threaded Programming in JAVAMulti-threaded Programming in JAVA
Multi-threaded Programming in JAVA
Vikram Kalyani
 
More topics on Java
More topics on JavaMore topics on Java
More topics on Java
Ahmed Misbah
 
Inter Thread Communicationn.pptx
Inter Thread Communicationn.pptxInter Thread Communicationn.pptx
Inter Thread Communicationn.pptx
SelvakumarNSNS
 
unit3multithreadingppt-copy-180122162204.pptx
unit3multithreadingppt-copy-180122162204.pptxunit3multithreadingppt-copy-180122162204.pptx
unit3multithreadingppt-copy-180122162204.pptx
ArunPatrick2
 
unit3 Exception Handling multithreadingppt.pptx
unit3 Exception Handling multithreadingppt.pptxunit3 Exception Handling multithreadingppt.pptx
unit3 Exception Handling multithreadingppt.pptx
ArunPatrick2
 
Sync, async and multithreading
Sync, async and multithreadingSync, async and multithreading
Sync, async and multithreading
Tuan Chau
 
Multithreading.pptx
Multithreading.pptxMultithreading.pptx
Multithreading.pptx
ssuserfcae42
 
Multithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of threadMultithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of thread
Kartik Dube
 
Multithreading in java programming language.ppt
Multithreading in java programming language.pptMultithreading in java programming language.ppt
Multithreading in java programming language.ppt
AutoAuto9
 
this power point presentation is about concurrency and multithreading
this power point presentation is about concurrency and multithreadingthis power point presentation is about concurrency and multithreading
this power point presentation is about concurrency and multithreading
Betty333100
 

Recently uploaded (20)

HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-UmgebungenHCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
panagenda
 
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
BookNet Canada
 
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Impelsys Inc.
 
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul
 
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes
 
Drupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy ConsumptionDrupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy Consumption
Exove
 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath MaestroDev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
UiPathCommunity
 
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
organizerofv
 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 
2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx
Samuele Fogagnolo
 
Heap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and DeletionHeap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and Deletion
Jaydeep Kale
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Cybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure ADCybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure AD
VICTOR MAESTRE RAMIREZ
 
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager APIUiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPathCommunity
 
How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?
Daniel Lehner
 
Quantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur MorganQuantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptxIncreasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Anoop Ashok
 
tecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdftecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdf
fjgm517
 
Technology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data AnalyticsTechnology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data Analytics
InData Labs
 
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-UmgebungenHCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
panagenda
 
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
BookNet Canada
 
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Impelsys Inc.
 
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul
 
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes
 
Drupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy ConsumptionDrupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy Consumption
Exove
 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath MaestroDev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
UiPathCommunity
 
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
organizerofv
 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 
2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx
Samuele Fogagnolo
 
Heap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and DeletionHeap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and Deletion
Jaydeep Kale
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Cybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure ADCybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure AD
VICTOR MAESTRE RAMIREZ
 
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager APIUiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPathCommunity
 
How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?
Daniel Lehner
 
Quantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur MorganQuantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptxIncreasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Anoop Ashok
 
tecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdftecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdf
fjgm517
 
Technology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data AnalyticsTechnology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data Analytics
InData Labs
 

22 multi threading iv

  • 1. Synchronization • When two or more threads need access to a shared resource, they need some way to ensure that the resource will be used by only one thread at a time. The process by which this is achieved is called synchronization. • Java provides unique, language-level support for it. Key to synchronization is the concept of the monitor (also called a semaphore). • A monitor is an object that is used as a mutually exclusive lock, or mutex. 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. These other threads are said to be waiting for the monitor. A thread that owns a monitor can reenter the same monitor if it so desires.
  • 2. • We can synchronize our code in either of two ways. Both involve the use of the synchronized keyword, and both are examined here. • Using synchronized Methods • The synchronized Statement • synchronized Methods : All objects have their own implicit monitor associated with them. To enter an object’s monitor, just call a method that has been modified with the synchronized keyword. While a thread is inside a synchronized method, all other threads that try to call it (or any other synchronized method) on the same instance have to wait. To exit the monitor and relinquish control of the object to the next waiting thread, the owner of the monitor simply returns from the synchronized method.
  • 3. class callme{ static int i=1; //synchronized static void print() { System.out.print("( HI "); try { Thread.sleep(1000); } catch(InterruptedException e) { System.out.println("Interrupted"); } System.out.println(i+" )"); i++; } } class A extends Thread { public void run() { for(int i=1;i<=5;i++) callme.print(); } }
  • 4. class B extends Thread{ public void run() { for(int i=1;i<=5;i++) callme.print(); } } class test { public static void main(String args[]) { A th1= new A(); th1.start(); // new A().start(); B th2=new B(); th2.start(); } }
  • 5. ( HI ( HI 1 ) 1 ) ( HI ( HI 3 ) ( HI 3 ) ( HI 5 ) ( HI 5 ) ( HI 7 ) ( HI 7 ) ( HI 9 ) 9 ) • Here the value of variable i is updated in unordered way by both the threads A and B. The output may change for each run. This can lead to a series problem if i is some important shared data or a control flag. The output printing is also not in order. To solve the problem we need synchronization over the print() method. • If the print() method is defined as: synchronized static void print(){---------}
  • 6. • Then the method is synchronized and the output will be-> ( HI 1 ) ( HI 2 ) ( HI 3 ) ( HI 4 ) ( HI 5 ) ( HI 6 ) ( HI 7 ) ( HI 8 ) ( HI 9 ) ( HI 10 ) • Also the output will remain same for each run.(As only one thread can execute the print() method at a time and other thread has to wait for completion of current call to print method.)
  • 7. • The synchronized Statement: While creating synchronized methods within classes that you create is an easy and effective means of achieving synchronization, it will not work in all cases. • Consider the following. Imagine that we want to synchronize access to objects of a class that was not designed for multithreaded access. That is, the class does not use synchronized methods. Further, this class was not created by us, but by a third party, and we do not have access to the source code. Thus, we can’t add synchronized to the appropriate methods within the class. How can access to an object of this class be synchronized? • The solution to this problem is quite easy: simply put calls to the methods defined by this class inside a synchronized block. synchronized(object) { // statements to be synchronized } • Here, object is a reference to the object being synchronized. A synchronized block ensures that a call to a method that is a member of object occurs only after the current thread has successfully entered object’s monitor.
  • 8. class callme{ int i=1; //non-static member void print() { //non-static member System.out.print("( HI "); try { Thread.sleep(1000); } catch(InterruptedException e) { System.out.println("Interrupted"); } System.out.println(i+" )"); i++; } } class A extends Thread { callme obj; A(callme target) { obj=target; } public void run() { for(int i=1;i<=5;i++) { synchronized(obj) { obj.print(); } } } }
  • 9. class B extends Thread{ callme obj; B(callme target){ obj=target; } public void run() { for(int i=1;i<=5;i++) { synchronized(obj) {obj.print(); } } } } class test { public static void main(String args[]) { callme obj1=new callme(); A th1= new A(obj1); th1.start(); // new A().start(); B th2=new B(obj1); th2.start(); } }
  • 10. • Here both thread are referring to the same instance/object of class callme. The call to method print() is in synchronized block this time. ( HI 1 ) ( HI 2 ) ( HI 3 ) ( HI 4 ) …….. ( HI 9 ) ( HI 10 ) So here without changing the original class callme the call to print method is executed in synchronized block. This will have the same effect as the previous case.(Where the print method is ynchronized.)
  • 11. Interthread Communication • Polling is usually implemented by a loop that is used to check some condition repeatedly. Once the condition is true, appropriate action is taken. This wastes CPU time. • To avoid polling, Java includes an elegant interprocess communication mechanism via the wait( ), notify( ), and notifyAll( ) methods. These methods are implemented as final methods in Object, so all classes have them. All three methods can be called only from within a synchronized context. • wait( ) tells the calling thread to give up the monitor and go to sleep until some other thread enters the same monitor and calls notify( ). • notify( ) wakes up the first thread that called wait( ) on the same object. • notifyAll( ) wakes up all the threads that called wait( ) on the same object. The highest priority thread will run first.
  • 12. • These methods are declared within Object, as shown here: final void wait( ) throws InterruptedException final void notify( ) final void notifyAll( )
  • 13. class A { public static void main(String[]args)throws InterruptedException { B b =new B(); b.start(); synchronized(b) //thread got lock { System.out.println("Calling wait method"); b.wait(); System.out.println("Got notification"); } System.out.println(b.total); } } class B extends Thread{ int total=0; public void run() { synchronized (this) //.thread got lock { System.out.println("Starting calculation"); for(int i=0;i<=1000;i++) { total=total+I; } System.out.println("Giving notification call"); notify(); //thread releases lock again }} }
  • 14. Calling wait method Starting calculation Giving notification call Got notification 500500