I cannot understand why I am getting deadlock in this simple sample.What is wrong with it?
public static void main(String[] args) {
Object data = null;
new Thread(new Producer(data)).start();
new Thread(new Consumer(data)).start();
}
}
class Producer implements Runnable {
private Object data;
public Producer(Object data) {
this.data = data;
}
@Override
public void run() {
while (true) {
while (data != null) {}
data = new Object();
System.out.println("put");
}
}
}
class Consumer implements Runnable {
private Object data;
public Consumer(Object data) {
this.data = data;
}
@Override
public void run() {
while (true) {
while (data == null) { }
data = null;
System.out.println("get");
}
}
When your produced “produces”, all it does is points its own
datareference to the new object, and the consumer has no way of knowing what happened. What you can do instead is make another classThen in your main do
Pass the ‘Data’ object to the consumer and producer, and use the get/set methods instead of assignment.
That way, both consumer and producer will be pointing to the same
Dataobject and when the producer produces or the consumer consumes, they will be changing the reference in the Data object, which they are sharing.