- 我做了一个线程等待和唤醒机制的练习.
- class Resource
- {
- private String name;
- private String sex;
- private boolean flag=false;
- public synchronized void intputMethod(String name,String sex)
- {
- if (flag)
- try{wait();}catch (InterruptedException e){}
- else
- {
- this.name=name;
- this.sex=sex;
- flag=true;
- notify();
- }
-
- }
- public synchronized void outputMethod()
- {
- if(!flag)
- try{wait();}catch (InterruptedException e){}
- else
- {
- System.out.println(name+"......."+sex);
- flag=false;
- notify();
- }
- }
- }
- class Intput implements Runnable
- {
- Resource a;
- Intput(Resource a)
- {
- this.a=a;
- }
- public void run()
- {
- int x=0;
- while(true)
- {
- if(x==0)
- a.intputMethod("丽丽","女女");
- else
- a.intputMethod("MIKE","男男");
- x=++x%2;
- }
- }
- }
- class Output implements Runnable
- {
- Resource a;
- Output(Resource a)
- {
- this.a=a;
- }
- public void run()
- {
- while(true)
- {
- a.outputMethod();
- }
- }
- }
- class Demo3
- {
- public static void main(String[] args)
- {
- Resource a=new Resource();
- Intput t1=new Intput(a);
- Output t2=new Output(a);
- Thread p1=new Thread(t1);
- Thread p2=new Thread(t2);
- p1.start();
- p2.start();
- }
- }
- 理想的输出结果是:丽丽........女女
- MIKE........男男
- 丽丽........女女
- MIKE........男男
- 以此无限循环
- 实际的输出结果是:丽丽........女女
- 丽丽........女女
- 丽丽........女女
- MIKE........男男
- MIKE........男男
- 我也知道了是因为多了intputMethod和outputMethod方法中的else所导致,但我不知道为什么求各位大神分析分析,谢谢了!
复制代码
|