日期:2014-05-20  浏览次数:20669 次

消费者生产者问题
本帖最后由 warrenwang1984 于 2014-03-10 17:18:32 编辑

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 WoTou {
int id; 
WoTou(int id) {
this.id = id;
}
public String toString() {
return "WoTou : " + id;
}
}

class SyncStack {
int index = 0;
WoTou[] arrWT = new WoTou[6];

public synchronized void push(WoTou wt) {
while(index == arrWT.length) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}

arrWT[index] = wt;
index ++;

this.notifyAll();
}

public synchronized WoTou pop() {

while(index <0) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}

index--;
this.notifyAll();
return arrWT[index];

}
}

class Producer implements Runnable {
SyncStack ss = null;
Producer(SyncStack ss) {
this.ss = ss;
}

public void run() {
for(int i=0; i<20; i++) {
WoTou wt = new WoTou(i);
ss.push(wt);
System.out.println("生产了:----" + wt);
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++) {
WoTou wt = ss.pop();
System.out.println("消费了: " + wt);
try {
Thread.sleep((int)(Math.random() * 500));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

运行结果中为什么出现这样的问题:用数组来模拟的话,应该是先进后出,但是在生产16和17的时候,结果不是这样的,而且貌似有下标越界了,怎么想都想不明白..求指导

生产了:----WoTou : 0
消费了: WoTou : 0
生产了:----WoTou : 1
生产了:----WoTou : 2
生产了:----WoTou : 3
生产了:----WoTou : 4
生产了:----WoTou : 5
消费了: WoTou : 5
生产了:----WoTou : 6
消费了: WoTou : 6
生产了:----WoTou : 7
消费了: WoTou : 7
消费了: WoTou : 4
生产了:----WoTou : 8
生产了:----WoTou : 9
生产了:----WoTou : 10
消费了: WoTou : 10
生产了:----WoTou : 11
消费了: WoTou : 11
生产了:----WoTou : 12
消费了: WoTou : 12
生产了:----WoTou : 13
消费了: WoTou : 13
生产了:----WoTou : 14
消费了: WoTou : 14
生产了:----WoTou : 15
消费了: WoTou : 15
生产了:----WoTou : 16
生产了:----WoTou : 17
消费了: WoTou : 16
消费了: WoTou : 17
生产了:----WoTou : 18
消费了: WoTou : 18
生产了:----WoTou : 19
消费了: WoTou : 19
消费了: WoTou : 9
消费了: WoTou : 8
消费了: WoTou : 3
消费了: WoTou : 2
消费了: WoTou : 1

------解决方案--------------------
这里的“打印”是向控制台 打印