可是优化完运行结果不是交替输出了,想不明白。这是为什么啊?复制代码
- class Res
- {
- private String name;
- private String sex;
- private boolean flag=true;
- public synchronized void set(String name,String sex)
- {
- if(flag)
- {
- this.name=name;
- this.sex=sex;
- flag=false;
- this.notify();
- }
- else
- {
- try{this.wait();}catch(Exception e){}
- }
- }
- public synchronized void put()
- {
- if(!flag)
- {
- System.out.println(name+"........."+sex);
- flag=true;
- this.notify();
- }
- else
- {
- try{this.wait();}catch(Exception e){}
- }
- }
- }
- class Input implements Runnable
- {
- private Res s;
- Input(Res s)
- {
- this.s=s;
- }
- public void run()
- {
- boolean b=true;
- while(true)
- {
- if(b)
- {
- s.set("张三"," 男");
- b=false;
- }
- else
- {
- s.set("LiLi"," female");
- b=true;
- }
- }
- }
- }
- class Output implements Runnable
- {
- private Res s;
- Output(Res s)
- {
- this.s=s;
- }
- public void run()
- {
- while(true)
- {
- s.put();
- }
- }
- }
- class Demo
- {
- public static void main(String[] args)
- {
- Res s=new Res();
- new Thread(new Input(s)).start();
- new Thread(new Output(s)).start();
- }
- }
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) | 黑马程序员IT技术论坛 X3.2 |