Inter Thread Communication(Producer-Consumer Problem) simplified

Inter thread communication is very interesting topic where you learn how two thread can talk to each other in a multi-threaded environment. And this is demonstrated with a very simple example of Producer-Consumer problem. Object class's wait and notify method will be used for inter thread communication.
I'm assuming two thread
  1. Producer
  2. Consumer

These will be spawned using main thread.

  • Producer will try producing Product. Produce action will be represented by making Available property in Product Object true. 
  • And consumer will be consuming that object by making available property false. 
  • Same object will be used to pass to both threads for inter thread communication
  • Code accessing same object will be synchronised 


Main methods used are :
Thread.sleep >> It will be used to give some delay so that we can understand code execution.
Object.wait >> Wait will be called on product which will make current thread to release lock and wait.
Object.notify >> Notify will be called on product object. This will make notify waiting thread and will allow to execute as soon as current thread goes to wait.
If you are not able to see code please access from here.


Output :
Product Consumed.
Product Produced.
Product Consumed.
Product Produced.
Product Consumed.
Product Produced.
Product Consumed.
Product Produced.
Product Consumed.

Comments

Popular posts from this blog

How to do AJAX using XMLHttpRequest for large data

Caching mechanisms in modern world browser

Polymorphism in Java OOP