Java | InterThread Communication

05 min read

Inter Thread Communication:

Another advantage of the thread: It avoids polling. (i.e., One thread polling and thus wasting more CPU cycles waiting for the other threads to finish etc)

This is done by wait(), notify() and notifyAll() methods of Object class and so all classes have them.

  • final void wait() throws InterruptedException

-tells the calling thread to give up the monitor and go to sleep until some other thread enters the monitor and calls notify()

  • final void notify()

-wakes up a thread that called wait() on the same object

  • final void notifyAll()

-wakes up all the threads that called wait() on the same object. One of the threads will be granted access.

Note: These methods can be called only from within a synchronized context.

Oracle recommends that calls to wait() should take place within a loop that checks the condition on which the thread is waiting.

Example:

Producer-Consumer Problem: The Consumer should consume only if the Producer produces and Producer should continue producing only if the consumer has consumed the already produced data.

POST A NEW COMMENT
     
  • Input (stdin)

    Output (stdout)


    Input (stdin)

    Your Output (stdout)

    Expected Output

    Compiler Message

    Input (stdin)

    2    3

    Your Output (stdout)

    5

    Expected Output

    5

    Compiler Message

    5

    Error