Java基础多线程间通讯示例操作(已优化)二:

class ThreadCommunicationDemo
{
    public static void main(String[] args)
    {
        Resource resource = new Resource();
        
        Input input = new Input(resource);
        Output output = new Output(resource);
        
        new Thread(input,"input thread").start();
        new Thread(output,"output thread").start();        
    }
}

class Input implements Runnable
{
    private Resource  resource;
    private boolean flag;
    public Input(Resource resource)
    {
        this.resource = resource;
    }
    
    public void run()
    {
        while(true)
        {
            if(flag)
            {
                resource.input("zhangsan","nan");
            }
            else
            {
                resource.input("lishi","nv");
            }
            
            flag=!flag;
        }
    }
    
}

class Output implements Runnable
{
    private Resource resource;
    
    public Output(Resource resource)
    {
        this.resource = resource;
    }
    
    public void run()
    {        
        while(true)
        {
            resource.output();            
        }
    }
    
}

class Resource
{
    private String Name;
    private String Sex;
    private boolean Flag;
    
    public String getName()
    {
        return this.Name;
    }
    
    public void setName(String Name)
    {
        this.Name = Name;
    }
    
    public String getSex()
    {
        return this.Sex;
    }
    
    public void setSex(String Sex)
    {
        this.Sex = Sex;
    }
    
    public Boolean getFlag()
    {
        return this.Flag;
    }
    
    public void setFlag(boolean Flag)
    {
        this.Flag = Flag;
    }
    
    public synchronized void input(String Name,String Sex)
    {
        if(this.getFlag())
            try{this.wait();}catch(Exception e){System.err.println(e.getMessage());}
            
        this.setName(Name);
        this.setSex(Sex);
        this.setFlag(true);        
        this.notify();
    }
    
    public synchronized void output()
    {
        if(!this.getFlag())
            try{this.wait();}catch(Exception e){System.err.println(e.getMessage());}
        
        System.out.println(this.getName() + " ... "+this.getSex());
        this.setFlag(false);
        this.notify();
    }
}
原文地址:https://www.cnblogs.com/cxmsky/p/2860855.html