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

java新人求助,帮看下问题分不多请谅解,呵呵!十一点熄灯前在线等谢谢!
Java code

class ProductorConsumer
{
    public static void main( String args[] )
    {
        Resource res=new Resource();// 创建共享资源
    
        new Thread( new Productor(res) ).start(); 
        new Thread( new Consumer(res) ).start();
    }
}
class Resource
{
    private int account=0;
    private boolean flag=false;
    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 synchronized void run()
    {
        while(res.flag)
            try
            {
                wait();
            }
            catch (Exception e)
            {
                System.out.println("error");
            }
        res.product();
        res.flag=true;
        this.notifyAll();
    }
}
class Consumer implements Runnable
{
    private Resource res;
    Consumer( Resource res )
    {
        this.res=res;
    }
    public synchronized void run()
    {
        while(!res.flag)
            try
            {
                wait();
            }
            catch ( Exception e )
            {
                System.out.println("error");
            }
        res.pay();
        res.flag=false;
        this.notifyAll();
    }
}


ProductorConsumer.java:34: 错误: flag可以在Resource中访问private
? while(res.flag)
? ^
ProductorConsumer.java:44: 错误: flag可以在Resource中访问private
? res.flag=true;
? ^
ProductorConsumer.java:57: 错误: flag可以在Resource中访问private
? while(!res.flag)
? ^
ProductorConsumer.java:67: 错误: flag可以在Resource中访问private
? res.flag=false;

------解决方案--------------------
class Resource {
? private int account=0;
? private boolean flag=false;

你这里flag是private,所以后面程序无法直接“res.flag”访问。

可以修改为:
boolean flag=false;

public boolean flag=false;