A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

package com.heima.code;
class ResourceDemo03{
        private String name;
        private String sex;
        public boolean flag = false;
        public synchronized void set(String name,String sex){
                if(flag)
                        try {
                                this.wait();
                               
                        } catch (Exception e) {}
                    this.name = name;
                    this.sex = sex;
                    flag = true;
                    this.notify();
        }
        public synchronized void outPut(){
                if(!flag)
                        try {
                                this.wait();                       
                        } catch (Exception e) {}
                    System.out.println(name+"........"+sex);
            flag = false;
                    this.notify();
        }         
}
class InputDemo03 implements Runnable{
        private ResourceDemo03 resd03;
       
        InputDemo03(ResourceDemo03 resd03){
                this.resd03 = resd03;
        }
        public void run(){
                int x = 0;
                while(true){
                        if(x==0)
                            resd03.set("Frank", "man");
                        else
                                resd03.set("小红", "woman");
                        x = (x+1)%2;
                }
        }
}
class OutputDemo03 implements Runnable {
        private ResourceDemo03 resd03;
        OutputDemo03(ResourceDemo03 resd03){
                this.resd03 = resd03;
        }
        public void run(){
                while(true){
                        resd03.outPut();
                }
        }
}
public class InputOutputThreadDemo03 {
        public static void main(String[] args) {
       ResourceDemo03 resd03 = new ResourceDemo03();
      
       new Thread(new InputDemo03(resd03)).start();
       new Thread(new OutputDemo03(resd03)).start();
     
      
        }

}

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马