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
These will be spawned using main thread.
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.
I'm assuming two thread
- Producer
- 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
Post a Comment