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

求教下面这个代码结果为什么是随机的?
在学同步时候练习用的 
目的是:pro put 0
  con get 0
  pro put 1
  con get 1
  ...
但是做出来后发现运行结果是随机的~虽然有时候能对上
求教错在哪里?

我怀疑两个synchronized方法是不是用的一个this的锁
但是我看不出怎么改 
求教求教 

代码如下:  
public class Wait 
{
  public static void main(String[] args) 
  {
  Queue q = new Queue();
  Producer pro = new Producer(q);
  Consumer con = new Consumer(q);
  pro.start();
  con.start();
  }
}
class Queue
{
  int value;
  boolean full = false;
  public synchronized void input(int i)
  {
  if(!full)
  {
  value=i;
  full=true;
  notify();
  }
  else
  {
  try
  {
  wait();
  }
  catch(Exception e)
  {
  e.printStackTrace();
  }
  }
   
   
   
  }
  public synchronized int output()
  {
  if(!full)
  { 
  try
  {
  wait();
  }
  catch(Exception e)
  {
  e.printStackTrace();
  }
   
  }
  else
  {
  full = false;
  notify();  
  }
  return value;
  }
}  
class Producer extends Thread
{
  Queue q;
  Producer(Queue q)
  {
  this.q = q;
  }
  public void run()
  {
  for(int i=0;i<10;i++)
  {
  q.input(i);
  System.out.println("Producer input "+i);
  }
  }
}
class Consumer extends Thread
{
  Queue q;
  Consumer(Queue q)
  {
  this.q = q;
  }
  public void run()
  {
  while(true)
  {
  System.out.println("Consumer get "+q.output());
  }
  }
}

------解决方案--------------------
Java code

public class Wait {
    public static void main(String[] args) {
    Queue q = new Queue();
    Producer pro = new Producer(q);
    Consumer con = new Consumer(q);
    pro.start();
    con.start();
    }
}

class Queue {
    int value;
    boolean full = false;

    public synchronized void input(int i) {
    if (!full) {
        value = i;
        full = true;
        notify();
    } else {
        try {
        wait();
        } catch (Exception e) {
        e.printStackTrace();
        }
    }

    }

    public synchronized int output() {
    if (!full) {
        try {
        wait();
        } catch (Exception e) {
        e.printStackTrace();
        }

    } else {
        full = false;
        notify();
    }
    return value;
    }
}

class Producer extends Thread {
    Queue q;

    Producer(Queue q) {
    this.q = q;
    }

    public void run() {
        for (int i = 0; i < 10; i++) {
        synchronized (this) {
            while (q.full == true); 
            q.input(i);
            System.out.println("Producer input " + i);
           
        }
        }

    }
}

class Consumer extends Thread {
    Queue q;
    Consumer(Queue q) {
    this.q = q;
    }

    public void run() {
        while (true) {
        synchronized (this) {
            while (q.full == false) ;        
             int temp = q.output();//这里顺便将值保存起来,以便退出这个线程,否则你的CPU很生气
            System.out.println("Consumer get " + temp);
            if(temp >=9) System.exit(0);
        }
        
    }

    }
}