黑马程序员技术交流社区

标题: 线程实例二(对实例一的优化) [打印本页]

作者: chenyanwei6    时间: 2016-12-23 21:21
标题: 线程实例二(对实例一的优化)
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();
     
      
        }

}





欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2