消费者、生产者问题之问题
public class Test{
public static void main(String args[]){
Queue q = new Queue();
Producer p =new Producer(q);
Consumer c = new Consumer(q);
p.start();
c.start();
}
}
//生产者线程
class Producer extends Thread{
Queue q;
public Producer(Queue q){
this.q = q;
}
public void run(){
for(int i=0;i<10;i++){
q.putValue(i);
System.out.println("Producer put:"+q.getValue());
}
}
}
//消费者线程
class Consumer extends Thread{
Queue q;
public Consumer(Queue q){
this.q = q;
}
public void run(){
while(true){
System.out.println("Consumer get:"+q.getValue());
}
}
}
//队列类
class Queue{
int value;
boolean bFull = false;
public synchronized void putValue(int i){
if(!bFull){//首先判断队列中又没有东西,没有则生产
this.value = i;
bFull = true;
}
notify();//提醒消费者去消费
try{
wait();//等待消费者消费完了之后通知它来生产
}
catch(Exception e){
e.printStackTrace();
}
}
public synchronized int getValue(){
if(!bFull){//先判断队列中是否有东西,没有则等待
try{
wait();
}
catch(Exception e){
e.printStackTrace();
}
}
bFull = false;
notify();//此处不能将生产者唤醒。。。。???????、、、、、、、
return value;
}
}
程序运行之后发现,消费者消费完第一个后,不能将生产者唤醒。处于死锁状态,不知道怎么解决