• 线程 生产者与消费者关系


    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();
        }
    
    }
  • 相关阅读:
    【搜索】棋盘 luogu-3956
    【动态规划】石子合并 luogu-1880
    【动态规划】合唱队形 luogu-
    【模拟】报名签到 luogu-4445
    【排序+贪心】导弹拦截 luogu-1158
    【模拟】不高兴的津津
    【模拟】选数 luogu-1037
    「JOISC2020」建筑装饰 4
    「清华集训」小 Y 和恐怖的奴隶主
    「CF708E」Student's Camp
  • 原文地址:https://www.cnblogs.com/zhuangjb/p/3190274.html
Copyright © 2020-2023  润新知