Can someone please tell me why this producer consumer problem is not passing fro
ID: 3704631 • Letter: C
Question
Can someone please tell me why this producer consumer problem is not passing from producer to consumer, but instead going into deadlock. Thanks
package producerconsumertest;
public class Consumer extends Thread {
private final BufferPoint buffer;
public Consumer(BufferPoint buffer){
this.buffer = buffer;
}
@Override
public synchronized void run(){
for(int i = 0; i< 10; i++){
while(!buffer.occupy()){
try {
wait();
} catch (InterruptedException ex) {
}
}
System.out.println("Reading "+ buffer.get()+" from buffer in iteration "+ i);
buffer.setoccupy(false);
notifyAll();
}
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package producerconsumertest;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Producer extends Thread {
private final BufferPoint buffer;
public Producer(BufferPoint buffer){
this.buffer = buffer;
}
@Override
public synchronized void run(){
int x;
int y;
for(int i = 0; i< 10; i++){
while(buffer.occupy()){
try {
wait();
} catch (InterruptedException ex) {
}
}
x = (int)(Math.random() * 100);
y = (int)(Math.random()*100);
buffer.set(x, y);
System.out.println("Writing "+ buffer.get()+" from buffer in iteration "+ i);
buffer.setoccupy(true);
notifyAll();
}
}
}
Explanation / Answer
In producer class, In the last but one line you have written buffer.setoccupy(true); this line is making the buffer to be occpied by the producer forever. that's why your program is going into deadlock.
To avoid this, that should be set to false. Because after writing the data into buffer producer should release the lock on the buffer and notify the consumer about it.
Change that line to buffer.setoccupy(false); and your program should work.
Please comment back incase you have any more doubts.