java2db

Inter thread communication in java



If two or more threads transfer or exchange information from one thread to another is called inter thread communication.

The methods  public final void notify()public final void notifyAll() and public final void wait() (from java.lang.Object class) works effectively for inter thread communication or thread dependency.

 

Inter thread communication in javapublic final void notify() : This method wakes up a single thread that is waiting on this object’s monitor. It sends a notification to a waiting thread that the object is available.

 

Inter thread communication in javapublic final void notifyAll() : This method wakes up one or more (all) threads that are waiting on this object’s monitor.It sends a notification to all  waiting threads at a time that the object is available.

 

Inter thread communication in javapublic final void wait() : Causes current thread to wait until another thread invokes the notify() or the notifyAll() method for this object,or if it elapsed specified amount of time.

 

 

In the below example we have two classes called Create and UseAfterCreation.

Create class thread  will add all the items to a java.util.List. If it finished the work, it calls the notify() or notifyAll() method to send notification to the waiting threads.

The thread from UseAfterCreation has been waiting for the notification from the Create class thread.So it will display the data , once it received the notification from the Create thread .

Inter thread communication in java

 

 

Inter thread communication in javaA simple example for inter thread communication :

Inter thread communication in java The class Create :

Inter thread communication in java The class  UseAfterCreation :

Inter thread communication in java Output :




Related Posts :
   [will not be published]



^ <