I am learning how to use the wait() and notify() methods by myself and I tried to make a simple program that outputs "Jack male"and "Jane female" alternately for 50 times. I have the resource class that includes the methods that my two threads are going to use. This is what it looks like:
public class ShareResource {
String name;
String gender;
boolean isEmpty = true;
synchronized public void push(String name, String gender) {
try {
while (isEmpty==false) {
this.wait();
}
this.name = name;
Thread.sleep(10);
this.gender = gender;
isEmpty = false;
this.notify();
} catch (Exception e) {
e.printStackTrace();
}
}
synchronized public void pop() {
try {
while (isEmpty) {
this.wait();
}
Thread.sleep(10);
System.out.println(this.name + " "+this.gender);
isEmpty = true;
this.notify();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class Producer implements Runnable{
private ShareResource resource=null;
public Producer(ShareResource resource){
this.resource=resource;
}
@Override
public void run() {
for (int i=0;i<50;i++){
if (i%2==0){
resource.push("Jack","male");
}else{
resource.push("Jane","female");
}
}
}
}
public class Consumer implements Runnable {
private ShareResource resource=null;
public Consumer(ShareResource resource){
this.resource=resource;
}
@Override
public void run() {
resource.pop();
}
}
public class Driver {
public static void main(String[] args){
ShareResource resource=new ShareResource();
new Thread(new Producer(resource)).start();
new Thread(new Consumer(resource)).start();
}
}
When I run the program, it only prints "Jack Male" once and nothing else. I assume there might be a block but I don't know where. Please help me about this!