Interthread Communication

Java provide benefit of avoiding thread pooling using interthread communication. The wait(), notify(), notifyAll() of Object class. These method are implemented as final in Object. All three method can be called only from within a synchronized context.

  • wait() tells calling thread to give up monitor and go to sleep until some other thread enters the same monitor and call notify.
  • notify() wakes up a thread that called wait() on same object.
  • notifyAll() wakes up all the thread that called wait() on same object.


Difference between wait() and sleep()

wait()sleep()
called from synchronised blockno such requirement
monitor is releasedmonitor is not released
awake when notify() or notifyAll() method is called.not awake when notify() or notifyAll() method is called
not a static methodstatic method
wait() is generaly used on conditionsleep() method is simply used to put your thread on sleep.

Thread Pooling

Pooling is usually implemented by loop i.e to check some condition repeatedly. Once condition is true appropriate action is taken. This waste CPU time.


Deadlock

Deadlock condition in Multithreading

Deadlock is a situation of complete Lock, when no thread can complete its execution because lack of resources. In the above picture, Thread 1 is holding a resource R1, and need another resource R2 to finish execution, but R2 is locked by Thread 2, which needs R3, which in turn is locked by Thread 3. Hence none of them can finish and are stuck in a deadlock.


Example of deadlock

class Pen{}
class Paper{}

public class Write {

  public static void main(String[] args)
  {
     final Pen pn =new Pen();
     final Paper pr =new Paper();
     
     Thread t1 = new Thread(){
            public void run()
            {
                synchronized(pn)
                {
                    System.out.println("Thread1 is holding Pen");
                  try{
                      Thread.sleep(1000);
                  }catch(InterruptedException e){}
                    synchronized(pr)
                {  System.out.println("Requesting for Paper"); }
                    
                }
            }
        };
      Thread t2 = new Thread(){
            public void run()
            {
                synchronized(pr)
                {
                    System.out.println("Thread2 is holding Paper");
                  try{
                      Thread.sleep(1000);
                  }catch(InterruptedException e){}
                    synchronized(pn)
                {  System.out.println("requesting for Pen"); }
                    
                }
            }
        };
        
        t1.start();
        t2.start();
  }
    
}

Output :

Thread1 is holding Pen
Thread2 is holding Paper