SlideShare ist ein Scribd-Unternehmen logo
1 von 14
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Was ist angesagt?

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
 
Thread model of java
Thread model of javaThread model of java
Thread model of java
myrajendra
 

Was ist angesagt? (20)

Learning Java 3 – Threads and Synchronization
Learning Java 3 – Threads and SynchronizationLearning Java 3 – Threads and Synchronization
Learning Java 3 – Threads and Synchronization
 
Multithreading Concepts
Multithreading ConceptsMultithreading Concepts
Multithreading Concepts
 
Multithreading in Java
Multithreading in JavaMultithreading in Java
Multithreading in Java
 
Life cycle-of-a-thread
Life cycle-of-a-threadLife cycle-of-a-thread
Life cycle-of-a-thread
 
Developing Multithreaded Applications
Developing Multithreaded ApplicationsDeveloping Multithreaded Applications
Developing Multithreaded Applications
 
Java Thread Synchronization
Java Thread SynchronizationJava Thread Synchronization
Java Thread Synchronization
 
Threading in C#
Threading in C#Threading in C#
Threading in C#
 
12 multi-threading
12 multi-threading12 multi-threading
12 multi-threading
 
Java Multithreading and Concurrency
Java Multithreading and ConcurrencyJava Multithreading and Concurrency
Java Multithreading and Concurrency
 
Multithreading
MultithreadingMultithreading
Multithreading
 
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)
 
Threads c sharp
Threads c sharpThreads c sharp
Threads c sharp
 
.NET: Thread Synchronization Constructs
.NET: Thread Synchronization Constructs.NET: Thread Synchronization Constructs
.NET: Thread Synchronization Constructs
 
multi threading
multi threadingmulti threading
multi threading
 
Java Multithreading
Java MultithreadingJava Multithreading
Java Multithreading
 
Thread model of java
Thread model of javaThread model of java
Thread model of java
 
javathreads
javathreadsjavathreads
javathreads
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Thread model in java
Thread model in javaThread model in java
Thread model in java
 
Java thread
Java threadJava thread
Java thread
 

Andere mochten auch

Spread spectrum
Spread spectrumSpread spectrum
Spread spectrum
Rina Ahire
 
Low noise amplifier csd
Low noise amplifier csdLow noise amplifier csd
Low noise amplifier csd
Rina Ahire
 

Andere mochten auch (20)

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

Ähnlich wie 22 multi threading iv

07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
nimbalkarvikram966
 
Multithreading
MultithreadingMultithreading
Multithreading
backdoor
 
Inter Thread Communicationn.pptx
Inter Thread Communicationn.pptxInter Thread Communicationn.pptx
Inter Thread Communicationn.pptx
SelvakumarNSNS
 

Ähnlich wie 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
 
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
 
Multithreading Presentation
Multithreading PresentationMultithreading Presentation
Multithreading Presentation
 
Thread syncronization
Thread syncronizationThread syncronization
Thread syncronization
 
Multithreading
MultithreadingMultithreading
Multithreading
 
Java programming PPT. .pptx
Java programming PPT.                 .pptxJava programming PPT.                 .pptx
Java programming PPT. .pptx
 
Oops
OopsOops
Oops
 
Multi-threaded Programming in JAVA
Multi-threaded Programming in JAVAMulti-threaded Programming in JAVA
Multi-threaded Programming in JAVA
 
advanced java ppt
advanced java pptadvanced java ppt
advanced java ppt
 
More topics on Java
More topics on JavaMore topics on Java
More topics on Java
 
Inter Thread Communicationn.pptx
Inter Thread Communicationn.pptxInter Thread Communicationn.pptx
Inter Thread Communicationn.pptx
 
Sync, async and multithreading
Sync, async and multithreadingSync, async and multithreading
Sync, async and multithreading
 
Threads in Java
Threads in JavaThreads in Java
Threads in Java
 
Multithreading.pptx
Multithreading.pptxMultithreading.pptx
Multithreading.pptx
 
Multithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of threadMultithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of thread
 
Md09 multithreading
Md09 multithreadingMd09 multithreading
Md09 multithreading
 
multithreading.pptx
multithreading.pptxmultithreading.pptx
multithreading.pptx
 
Java
JavaJava
Java
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 

Kürzlich hochgeladen

Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 

Kürzlich hochgeladen (20)

Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdf
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 

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