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

java中生产者与消费者问题的几点疑问
问题:线程没有被唤醒造成死锁。
求高手帮忙。。


package com.thread.sjx;
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(p).start();
new Thread(p).start();
new Thread(c).start();
new Thread(c).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) {
System.out.println(index);
while(index == arrWT.length) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
return;
}
this.notifyAll();
arrWT[index] = wt;
index ++;
}

public synchronized WoTou pop() {
System.out.println(index);
while(index == 0) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
this.notifyAll();
index--;
return arrWT[index];
}
}

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

public void run() {
for(int i=0; i<40; 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<40; i++) {
WoTou wt = ss.pop();
System.out.println("消费了: " + wt);
try {
Thread.sleep((int)(Math.random() * 1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
------最佳解决方案--------------------
产生死锁的原因是方法push(WoTou wt) 里的return语句。
假设某个Producer线程在放入第10个WoTou对象时,数组已经满了,这时线程进入 wait(). 当消费(Consumer)线程消费一个WoTou对象时,会唤醒这个等待线程,这时程序应该接着执行,把这第10个WoTou放入数组。 而楼主的代码,来了个return. 那这第10个WoTou就丢失了,(没放入数组)。等到循环完40次时,没有放入40个Wotou.假设只放了38个,而消费线程是要消费40个的,把38个消费完后,剩下的两个只有永远等待下去了。
所以楼主的代码,只要把return 语句删掉即可。(存入和取出都删掉,return会使程序逻辑混乱。)


------其他解决方案--------------------

import java.util.Random;

public class ProducerConsumer {
public static final int TMIE = 1000;

public static void main(String[] args) {
SyncStack ss = new SyncStack();
Producer p = new Producer(ss);