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

求大侠帮助..看看这道面试题
Java code


 The Producer generates an integer between 0 and 9 (inclusive),stores it in a “CubbyHole” 
       object, and prints the generated number.
            class Prodecer extends Thread{
              private CubbyHole cubbhole;
              private int number;
               
                public Prodecer(CubbyHole c, int number){
cubbhole = c;
this.number = number;
}
public void run(){
   for(int i=0;i<10;i++){
      cubbhole.put(i);
      System.out.println(“Producer#”+this.number+”put:”+i);
      try{

}catch(InterruptedException e){
}
}
}

The Consumer,being ravenous,consumers all intergers from the CubbyHole(the exact same object into which the Producer put the integers in the first place ) as quickly as the become available.

class Consumer extends Thread{
              private CubbyHole cubbhole;
              private int number;
              public Consumer(CubbyHole c, int number){
cubbhole = c;
this.number = number;
}

public void run(){
   int value = 0;
   for(int i=0;i<10;i++){
     value = cubbhole.get();
     System.out.println(“Consumer #”+this.number+”got:”+value);
}
}
}

The Producer and Consumer in this example share data through a common CubbyHole object. And you will note that neither ahte Producer nor the Consumer make any effort whatsoever ato ensure that the Consumer is getting each value produced once and only once. The synchronization between these two threads actually occurs at a lower
        level,within the get() and put() methods of the CubbyHole object.
           
            The Main Program 
                    class ProducerConsumerTestP{
         public static void main(String[] args){
         CubbyHole c = new CubbyHole();
        Producer p1 = new Producer(c,1);
        Consumer c1=new Consumer(c,1);
            p1.start();
        c1.start();
}
}
请补充CubbyHole的代码
    class CubbyHole{
    private int contents;
    private boolean available = false;
    public synchronized int get(){
    while(available = = false){
try{
____(1)______;
}catch(InterruptedException e){
}
}
available=____(2)______;
 __________;
  return contents;
}
public synchronized void put(int value){
    while(available = = true){
try{
____(3)______;
}catch(InterruptedException e){
}
}
  Contents = value;
available=____(4)______;
 ____(5)______;
}
}




------解决方案--------------------
这样行吗?
1 notify();wait();
2 false; 
3 Thread.sleep(1);wait();
4 true;
5 notify();

------解决方案--------------------
我觉得是:
1.wait();
2.false;notify();
3.wait();
4.true;
5.notify();
------解决方案--------------------
探讨
我觉得是:
1.wait();
2.false;notify();
3.wait();
4.true;
5.notify();

------解决方案--------------------
探讨

引用:
我觉得是:
1.wait();
2.false;notify();
3.wait();
4.true;
5.notify();

把notify改成notifyAll就行了