线程 生产者与消费者关系

class Info{
    private String name="oracle";
    private String desc="数据库";
    private boolean flag=false;
    public synchronized void set(String name,String desc){
        if(!this.flag){
        try{
            super.wait();    
        }
        catch(Exception e){}
        }
        this.setName(name);
        try{Thread.sleep(300);}
        catch(Exception e){}
        this.setDesc(desc);
        this.flag=false;
        super.notify();
    }
    
    public synchronized void get(){
        if(this.flag){
        try{super.wait();}
        catch(Exception e){}
        }
        try{Thread.sleep(300);}
        catch(Exception e){}
        System.out.println(this.getName()+"-->"+this.getDesc());
        this.flag=true;
        super.notify();
        
    }
    public void setName(String name){
        this.name=name;
    }
    public void setDesc(String desc){
        this.desc=desc;
    }
    public String getName(){
        return this.name;
    }
    public String getDesc(){
        return this.desc;
    }
}

class Pro implements Runnable{
    private Info info;
    public Pro(Info info){
        this.info=info;
    }
    public void run(){
        for(int x=0;x<50;x++){            
            if(x%2==0){
                this.info.set("Java","www.sun.com");
                try{
                    Thread.sleep(300);
                }
                catch(Exception e){}
                
            }else{
                this.info.set("oracle","数据库");
                try{
                    Thread.sleep(300);
                }catch(Exception e){}        
            }
        }
    }
}

class Cus implements Runnable{
    private Info info;
    public Cus(Info info){
        this.info=info;
    }
    public void run(){
        for(int x =0;x<50;x++){
            try{
                Thread.sleep(300);
            }catch(Exception e){}
            this.info.get();
        }
    }
}


public class CommDemo {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Info info=new Info();
        Pro p=new Pro(info);
        Cus c=new Cus(info);
        new Thread(p).start();
        new Thread(c).start();
    }

}

 

posted @ 2013-07-14 23:14  孤叶情枫  阅读(248)  评论(0编辑  收藏  举报