public class ProducerConsumer {
public static void main(String[] args) {
SyncStack ss = new SyncStack();
Producer p = new Producer(ss);
Consumer c = new Consumer(ss);
new Thread(p).start();
new Thread(c).start();
}
}
class WaWa {
int id;
WaWa(int id) {
this.id = id;
}
public String toString() {
return "WaWa : " + id;
}
}
class SyncStack {
int index = 0;
WaWa[] arrWW = new WaWa[6];
public synchronized void push(WaWa ww) {
while(index == arrWW.length) {
try {
this.wait();//A处
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.notifyAll(); //1处
arrWW[index] = ww;
index ++;
}
public synchronized WaWa pop() {
while(index == 0) {
try {
this.wait();//B处
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.notifyAll();//2处
index--;
return arrWW[index];
}
}
class Producer implements Runnable {
SyncStack ss = null;
Producer(SyncStack ss) {
this.ss = ss;
}
public void run() {
for(int i=0; i<20; i++) {
WaWa ww = new WaWa(i);
ss.push(ww);
System.out.println("生产了:" + ww);
try {
Thread.sleep((int)(Math.random() * 200));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Consumer implements Runnable {
SyncStack ss = null;
Consumer(SyncStack ss) {
this.ss = ss;
}
public void run() {
for(int i=0; i<20; i++) {
WaWa ww = ss.pop();
System.out.println("消费了: " + ww);
try {
Thread.sleep((int)(Math.random() * 1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
麻烦请问一下关于这个程序1处和2处的notify叫醒的分别是哪个wait,最好说一下执行过程谢谢
|
|