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

求助!一个小程序
Java code

class ProductorConsumer
{
    public static void main( String args[] )
    {
        Resource res=new Resource();// 创建共享资源
    
        new Thread( new Productor(res) ).start();
        new Thread( new Productor(res) ).start();
        new Thread( new Consumer(res) ).start();
        new Thread( new Consumer(res) ).start();
    }
}
class Resource
{
    private int account=0;
    private boolean flag=false;
    public boolean getFlag()
    {
        return flag;
    }
    public void setFlag(boolean a)
    {
        flag=a;
    }
    public void product()
    {
        account++;
        System.out.println(Thread.currentThread().getName()+"生产"+account);
    }
    public void pay()
    {
        System.out.println("\t\t\t"+Thread.currentThread().getName()+"消费"+account);
    }
}
class Productor implements Runnable
{
    private Resource res;
    Productor(Resource res)
    {
        this.res=res;
    }
    public void run()
    {
        synchronized(res)
        {
            while(res.getFlag())
                try
                {
                    this.wait();
                }
                catch (Exception e)
                {
                    System.out.println("error");
                }
            res.product();
            res.setFlag(true);
            this.notifyAll();
        }

    }
}
class Consumer implements Runnable
{
    private Resource res;
    Consumer( Resource res )
    {
        this.res=res;
    }
    public void run()
    {
        synchronized(res)
        {
            while(!res.getFlag())
                try
                {
                    this.wait();
                }
                catch ( Exception e )
                {
                    System.out.println("error");
                }
            res.pay();
            res.setFlag(false);
            this.notifyAll();
        }
        
    }
}




为什么一直都是error啊,wait()怎么就异常了呢?求解

------解决方案--------------------
不对,改成:
res.wait();
res.notify();