How Inter Thread Communication Happens In Java?

0
39
Spread the love
  • 1
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
    1
    Share

Inter Thread Communication
Inter Thread Communication

Inter Thread Communication:

Before you start reading  this post please read this post for thread creation concept,read this post for actual thread class and read this life cycle of a thread. These links will give you a better idea how a thread works. Coming back to the topic,Inter thread communication happens in three ways.

  • Through common shared data
  • Using thread control methods
  • Through inter process communication
Through common shared data

All the threads in the same program share the same memory space.If an object is accessible to various thread then these threads share access to that object’s data members and thus communicate with each other.

Using thread control methods

There are three ways by which threads communicate to each other by this technique.
They are as follows:

  1. suspend();–> A thread can suspend itself and waits for another thread to resume it.
  2. resume();–>A thread can wake another thread (waiting state) through resume method. Then they can run concurrently.
  3. join()–>This method is used for caller thread to wait for completion of the called thread.
Through inter process communication

There are three methods available for inter process communication in this technique. They are as follows:

  1. wait();–>This method tells the caller thread to give up the monitor and make the calling thread wait until either a time out occurs or another thread calls the same thread’s notify() or notifyAll() method.
  2. notify();–>This method wakes up the only one(first) waiting thread called wait() or the same object
  3. notifyAll();–>This method will wake up all the threads that have been called by wait() on the same object.
These three methods are defined in class -Object under java.lang package.These three methods provide an elegant interprocess communication mechanism to take care of a deadlock situation in java.
A deadlock may occur when a thread holding the key of the monitor is suspended or is kept waiting for another thread’s completion. If the other thread is waiting or needs to get into same monitor,both threads will be waiting for ever.
Don't miss out!
Subscribe To Newsletter

Receive top technical news, lesson ideas, travel tips and more!

Invalid email address
Give it a try. You can unsubscribe at any time.

Spread the love
  • 1
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
    1
    Share

LEAVE A REPLY

Please enter your comment!
Please enter your name here