Turn Desktop View Off
You are here:   HomeJava ProgrammingMultithreadingExplain Inter-Thread Communication in Multithreading
by Dinesh Thakur Category: Multithreading

If we talk about the mechanism of synchronization, then as one thread exits from the monitor then it must inform the waiting threads that it has left the monitor, now suspended thread can proceed to acquire the lock on the resources or entered in the monitor. If that is not possible then the waiting thread will always be in the waiting list. So, to solve this problem threads must communicate with each other.

Java provides a set of methods by which they can communicate to each other.

Object class has some final methods for such purposes. All these methods can be called only from the synchronized context.

wait() tells the calling thread to leave the monitor and go to sleep until some other thread enters the same monitor and calls notify( ).

notify() give a wake up signal or call to the first thread that called wait( ) on the same object.

notify All( ) give a wake up signal or call to 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( )

 

Example:

 

public class CubbyHole

{

           private int contents;

           private boolean available false; 

           public synchronized int get()

       {

            while (available == false)

                 {

                       try

                     {

                       wait ();

                      }

                       catch (InterruptedException e) { }

                  }

                       available = false;

                       notifyAll();

                       return contents;

          }

                public synchronized void put(int value)

                {

                   while (available == true)

                       {

                          try

                            {

                                 wait();

                            }

                                 catch (InterruptedException e) { }

                        }

                                 contents = value;

                                 available = true;

                                 notifyAll();

                  }

}





Subscribe To Free Daily Newsletter!

Get Free News Updates Delivered Directly To Your Inbox
About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular Computer Notes blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to contact us.



What's New and Popular





Popular Article