public class ProConsumer{
public static void main(String[] args) {
Signal S = new Signal();
Thread tProducer = new Thread(new Producer(S));
Thread tConsumer = new Thread(new Consumer(S));
tProducer.start();
tConsumer.start();
}
}
class Signal{
boolean canUse = false;
public synchronized void put(int i){
if(canUse == false){
canUse = true;
notify();
System.out.println("signal = " + i + ": put successed!");
} else
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public synchronized void get(int i){
if(canUse == true){
canUse = false;
notify();
System.out.println("signal = " + i + ": get successed!");;
} else
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class Producer implements Runnable{
Signal S;
Producer(Signal S){
this.S = S;
}
public void run() {
for(int i = 0; i < 5; i++){
S.put(i);
}
}
}
class Consumer implements Runnable{
Signal S;
Consumer(Signal S){
this.S = S;
}
public void run() {
for(int i = 0; i < 5; i++){
S.get(i);
}
}
}