Producer-Consumer Problem:
This problem arises if there is no communication between producer and consumer thread.
1.producer will produce the item which leads to buffer overflow.
2.consumer will try to consume the item until buffer underflow arises.
To avoid these issues and utilize cpu time efficiently we are going to use wait(),notify(),notifyAll():
- final void wait( ) throws InterruptedException
- wait( ) tells the calling thread to give up the monitor and go to sleep until some other thread enters the same monitor and calls notify( ) or notifyAll( ).
- final void notify( )
- notify( ) wakes up a thread that called wait( ) on the same object.
- final void notify All( )
- notifyAll( ) wakes up all the threads that called wait( ) on the same object. One of the threads will be granted access.
Following program illustrates the same scenario
Main class which creates object for other classes
Consumer thread
producer thread
Queue /Buffer class with get() and put()
The output of program when its executed is as follows:
The following program keeps on producing the output unless we press ctrl-c.As we dont have any restriction on buffer.
No comments:
Post a Comment