Previously we have discussed about
![]() |
| Inter-Thread Communication Methods |
Inter Thread Communication
Inter Thread Communication means exchange of messages between two or more threads.The Transfer of messages takes place before or after the change of state of Thread.
For Example an active thread may notify to another suspended thread just before switching to the suspend state. Java Implements inter thread communication with the help of the following three methods: wait(), notify() and notifyall().
These methods are implemented as final methods in object class , so all classes have these methods.
wait() : This method tells calling thread to give up and go to sleep untill some other thread enters the same state and calls notify() or notifyall(). The Object class declaration of notifyall() method is shown below :
final void wait()
notify() : It Resume the thread that went into the sleep state.The Object class declaration of notifyall() method is shown below :
final void notify()
notifyall() : It Resume all threads that went into the sleep state.The execution of these threads happens as per per priority.The Object class declaration of notifyall() method is shown below :
final void notifyall()
Example of Inter Thread Communication:
class User{
int rs = 500;
synchronized void get(int rs){
System.out.println("Getting Rs ");
if(this.rs < rs){
System.out.println("Less Rupees ");
try {
wait();
} catch (Exception e) {
e.printStackTrace();
}
}
this.rs = rs;
System.out.println("Getting Rs Completed ..");
}
synchronized void put(int rs){
System.out.println("Depositing Rs..");
this.rs += rs;
System.out.println("Depositing Completed.");
notify();
}
}
public class InterThreadCommunicationExample1 {
public static void main(String[] args) {
User u = new User();
new Thread(){
public void run(){
u.get(1000);
}
}.start();
new Thread(){
public void run(){
u.put(200);
}
}.start();
}
}
Program Output:
Getting Rs
Less Rupees
Depositing Rs..
Depositing Completed.
Getting Rs Completed ..
Blog Author - Pushkar Khosla,
Software Developer by Profession with 3.0 Yrs of Experience , through this blog i'am sharing my industrial Java Knowledge to entire world. For any question or query any one can comment below or mail me at pushkar.itsitm52@gmail.com.
This blog is all about to learn Core Java ,Interview Programs and Coding tricks to polish your Java Knowledge. If you like the content of this blog please share this with your friends.
Software Developer by Profession with 3.0 Yrs of Experience , through this blog i'am sharing my industrial Java Knowledge to entire world. For any question or query any one can comment below or mail me at pushkar.itsitm52@gmail.com.
This blog is all about to learn Core Java ,Interview Programs and Coding tricks to polish your Java Knowledge. If you like the content of this blog please share this with your friends.
Java I/O Tutorial

No comments:
Post a Comment