黑马程序员技术交流社区

标题: 等待唤醒机制 [打印本页]

作者: 周飞飞    时间: 2015-8-12 10:46
标题: 等待唤醒机制
package day12;

class Rec2 {
        private String name ;
        private String sex;
        private boolean flag;
        public synchronized void set(String name,String sex){
                if(this.flag)
                        try {this.wait();} catch (InterruptedException e) {}
                this.name = name;
                this.sex = sex;
                flag = true;
                this.notify();
               
        }
        public synchronized void get(){
                if(!this.flag)
                        try {this.wait();} catch (InterruptedException e) {}
                System.out.println(this.name+"......."+this.sex);
                flag = false;
                this.notify();
        }
}
class Input2 implements Runnable{
        private Rec2 r;
        Input2(Rec2 r){
                this.r= r;
        }
        public void run(){
                int x = 0;
                while(true){
                       
                        if(x==0)
                                r.set("zhangsan", "man");
                        else
                                r.set("李四", "女女女");
               
                        x = (x+1)%2;
                }
       
        }
}
class Output2 implements Runnable{
        private Rec2 r;
        Output2(Rec2 r){
                this.r = r;
        }
        public void run(){
                while(true){
                        r.get();
                }
        }
}
public class InputOutputDemo2 {
        public static void main(String args[]){
                Rec2 r = new Rec2();
                new Thread(new Input2(r)).start();
                new Thread(new Output2(r)).start();
        }

}

作者: 风华正茂    时间: 2015-8-12 12:41
谢谢楼主分享,好帖必须顶
作者: 耀阳圣尊    时间: 2015-8-12 14:47
悄悄告诉大家一个好消息,这个要重点掌握哦!




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