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

生产者消费者打印问题
为什么这个程序执行后没有打印结果??
package day12;

public class ProducerConsumerDemo {

/**
 * @param args
 */
public static void main(String[] args) {
Resource res = new Resource();
Producer pro = new Producer(res);
Consumer con = new Consumer(res);
Thread t1 = new Thread(pro);
Thread t2 = new Thread(con);
t1.start();
t2.start();
}

}

 class Resource{
 private String name;
 private boolean flag = false;
 private int count = 1;
 public synchronized void set(String name){
 while(flag){
 try{wait();}catch(Exception e){}
 this.name = name + "-------" + count++;
 System.out.println(Thread.currentThread().getName()+"....生产者...."+this.name);
 flag = true;
 this.notifyAll();
 }
 }
 public synchronized void out(){
 while(!flag){
 try{wait();}catch(Exception e){}
 System.out.println(Thread.currentThread().getName()+"....消费者...."+this.name);
 flag = false;
 this.notifyAll();
 }
 }
 }
 
 class Producer implements Runnable{
 private Resource res;
 Producer(Resource res){
 this.res = res;
 }
 public void run(){
 while(true){  
 res.set("+商品+");
 }
 }
 }
 
 class Consumer implements Runnable{
 
 private Resource res;
 Consumer(Resource res){
 this.res = res;
 }
 public void run(){
 while(true){  
 res.out();
 }
 }
 }

------解决方案--------------------
out方法中判断 while(!flag) 条件成立, wait()住了。

set方法中判断 while(flag)  条件不成立,循环退出,out线程永远wait住了