我晕了,把你的两个IF改成While就行了嘛。
while(bfull)
{
    wait();                
}while(!bfull)
{
    wait();                
}

解决方案 »

  1.   

    噢,还忘了,notify要改成notifyAll,要不然会产生死锁。
      

  2.   

    哈哈。好啦。你真行。等会儿给你加分啊。我还想问一下。为什么用notify就会死锁?
      

  3.   

    因为notify只会在等待的线程队列里随机挑选一个来唤醒。例如,在某个Customer调用notify的时刻,在等待的线程就是另外两个Customer和那唯一的一个Producer。如果下一个被唤醒的是Producer,它的运行条件满足,可以继续走下去。如果下一个被唤醒的是其中一个Customer,因为这个时候bfull还是false,它的运行条件不满足,又要进入等待队列,这样所有的线程都处于等待状态,就死锁了。NotifyAll的话,保证了每次producer都会被唤醒。=======================================================================三个customer线程被唤醒的顺序是随机的,某个customer可能连续被优先唤醒,而另外一个连续几次都不满足条件,所以它们能运行完get方法的次数是不相等的。如果你想它们按照1→2→3→1→2→3这样的有序循环,那就复杂一点,需要增加标志位。
      

  4.   

    Production:public class Production {
        private int size;
        private int totalSize;
        public int getTotalSize() {
            return totalSize;
        }    public int getSize() {
            return size;
        }    public synchronized void input() {
            this.size++;
            totalSize++;
            System.out.println("production   size   is   " + this.size);
            System.out.println("production   total size   is   " + this.totalSize);
        }    public synchronized void get() {
            //try{Thread.sleep(10);}catch(Exception   e){} 
            this.size--;
            System.out.println(Thread.currentThread().getName() + "   is   running   and   production   size   is   " + this.size);
            System.out.println("production   total size   is   " + this.totalSize);
        }
    }
    Producerpublic class Producer implements Runnable {    Production p = null;    public Producer(Production p) {
            this.p = p;
        }    @Override
        public void run() {
            //int i;
            while (p.getTotalSize() < 50) {
                p.input();
            }
        }
    }
    Consumerpublic class Consumer implements Runnable {    Production p = null;    public Consumer(Production p) {
            this.p = p;
        }    public void run() {
            while (p.getSize() > 0 && p.getTotalSize() <= 50) {
                p.get();
            }
        }
    }
      

  5.   

    这个可以了.可是不知道是哪个地方的条件有问题,最后size会被多取一次,成了-1
      

  6.   

    favorite7w :哈哈。你说的我明白啦。呵呵。谢谢你。还想问一下你说的“如果你想它们按照1→2→3→1→2→3这样的有序循环”是不是指customer按那个顺序显示?
      

  7.   

    yuanyuan110_l :也谢谢你。哈哈。不错。那个小错误我再看看。一会给你两散分。给你们一人50不知道行不行?要不行就说。我再给加点。呵呵。
      

  8.   

    在Production的get方法中加上判断
    if(size < 1) {
      return;
    }
      

  9.   

    给每个Customer分配一个ID。在Production设置一个标志位,标识当前应该轮到那个Customer获取Production。在get方法,除了要判断bfull是否满足条件外,还要把ID号和标志位匹配一下,判断下是否轮到当前的Customer获得Production。还要在get方法最后notifyAll之前,将标志位切换到下一个Customer的ID。以此循环。