package code;class CubbyHole
{
public int content;
private boolean available=false; public synchronized int get()
{
          while(available==true)
   {
try{
wait();
}catch(InterruptedException e)
{
System.out.println(e);
}
}
available=false;
notifyAll();
System.out.println("Consumer:"+" get:"+ content);
return content;
} public synchronized void put(int value){
while(available==false)
{
try{
wait();
}catch(InterruptedException e)
{
System.out.println(e);
}
content=value;
available=true;
notifyAll();
System.out.println("Consumer:"+" put:"+ value);
}
}
}
class Producer extends Thread
{
private CubbyHole cubbyhole;
public Producer(CubbyHole c)
{
cubbyhole=c;
}
public void run()
{
for(int i=0;i<10;i++)
{
cubbyhole.put(i);
// System.out.println("Producer"+" put:"+ i);
try{
sleep(1000);
}catch(InterruptedException e)
{
System.out.println(e);
}
}
}
}
class Consumer extends Thread
{
private CubbyHole cubbyhole;
public Consumer(CubbyHole c)
{
cubbyhole=c;
}
public void run()
{
int value;
for(int i=0;i<10;i++)
{
value=cubbyhole.get();
try{
sleep(1000);
}catch(InterruptedException e)
{
System.out.println(e);
}
}
}
}
public class Demo
{
public static void main(String[] args)
{
CubbyHole h=new CubbyHole();
Producer p=new Producer(h);
Consumer c=new Consumer(h);
p.start();
c.start();
}
}
不知道这程序错在哪,就是不能达到我要的效果,就是产生一个,取一个!

解决方案 »

  1.   

    修改你的get和put方法 public synchronized int get() {
    if (!available) {
    try {
    wait();
    } catch (InterruptedException e) {
    System.out.println(e);
    }
    }
    available = false;
    notifyAll();
    System.out.println("Consumer:" + " get:" + content);
    //
    // while (available == true) {
    // try {
    // wait();
    // } catch (InterruptedException e) {
    // System.out.println(e);
    // }
    // available = false;
    // notifyAll();
    // System.out.println("Consumer:" + " get:" + content);
    // }
    return content;
    } public synchronized void put(int value) {
    if (available) {
    try {
    wait();
    } catch (InterruptedException e) {
    System.out.println(e);
    }
    }
    content = value;
    available = true;
    notifyAll();
    System.out.println("Consumer:" + " put:" + value);
    // while (available == false) {
    // try {
    // wait();
    // } catch (InterruptedException e) {
    // System.out.println(e);
    // }
    // content = value;
    // available = true;
    // notifyAll();
    // System.out.println("Consumer:" + " put:" + value);
    // }
    }