zoukankan      html  css  js  c++  java
  • 线程 生产者与消费者关系

    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();
        }
    
    }
  • 相关阅读:
    第52节:String,权限修饰符,方法,集合
    String,权限修饰符,方法,集合
    String,权限修饰符,方法,集合
    第51节:Java当中的集合框架Map
    Java当中的集合框架Map
    Java当中的集合框架Map
    Java的当中的泛型
    Java的当中的泛型
    第50节:Java的当中的泛型
    小程序当中的文件类型,组织结构,配置,知识点等
  • 原文地址:https://www.cnblogs.com/zhuangjb/p/3190274.html
Copyright © 2011-2022 走看看