What is the issue with this Producer Consumer Problem. Can you fix it.
public class ProducerConsumerProb {
public static void main(String[] args) {
Container container = new Container();
Turn turn = Turn.PRODUCER;
Producer p = new Producer(container, turn);
Consumer c = new Consumer(container, turn);
Thread pro = new Thread(p);
Thread con = new Thread(c);
pro.start();
con.start();
}
public static class Producer implements Runnable{
Container container;
Turn turn;
public Producer(Container integer,Turn turn) {
this.container = integer;
this.turn = turn;
}
@Override
public void run() {
for(int i=0;i<10;i++){
Turn temp = null;
while(true){
synchronized (turn) {
temp = turn;
}
if(temp == Turn.PRODUCER){
break;
}
}
synchronized (turn) {
container.setI(i);
turn = Turn.CONSUMER;
}
}
}
}
public static class Consumer implements Runnable{
Container container;
Turn turn;
public Consumer(Container integer,Turn turn) {
this.container = integer;
this.turn = turn;
}
@Override
public void run() {
for(int i=0;i<10;i++){
Turn temp = null;
while(true){
synchronized (turn) {
temp = turn;
}
if(temp == Turn.CONSUMER){
break;
}
}
synchronized (turn) {
System.out.println(container.getI());
turn = Turn.PRODUCER;
}
}
}
}
public static class Container{
Integer i = new Integer(0);
public int getI() {
return i;
}
public void setI(int i) {
this.i = i;
}
}
enum Turn{
PRODUCER,CONSUMER;
}
}
At first glance a while block with a constant condition value should be avoided and use the synchronize block as the wait mechanism.
- Aurelien May 30, 2018Secondly, the Turn enum must be mutable and their instances must be modified accordingly. Here you are not modifying the object, you are simply swapping references(turn = Turn.PRODUCER;) which means "turn" in the Producer and "turn" in Consumer are not pointing to the same value in heap memory.