本帖最后由 罗广伟 于 2013-6-7 15:30 编辑
//等待唤醒机制代码- class Res
- {
- private String name;
- private String sex;
- private 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 out()
- {
- if(!flag)
- try{this.wait();}catch(Exception e){}
- System.out.println(name+"........"+sex);
- flag = false;
- this.notify();
- }
- }
- class Input implements Runnable
- {
- private Res r ;
- Input(Res r)
- {
- this.r = r;
- }
- public void run()
- {
- int x = 0;
- while(true)
- {
- if(x==0)
- r.set("mike","man");
- else
- r.set("丽丽","女女女女女");
- x = (x+1)%2;
- }
- }
- }
- class Output implements Runnable
- {
- private Res r ;
-
- Output(Res r)
- {
- this.r = r;
- }
- public void run()
- {
- while(true)
- {
- r.out();
- }
- }
- }
- class InputOutputDemo2
- {
- public static void main(String[] args)
- {
- Res r = new Res();
- Input in = new Input(r);
- Output out = new Output(r);
- Thread t1 = new Thread(in);
- Thread t2 = new Thread(out);
- t1.start();
- t2.start();
- }
- }
复制代码 //问题:Res类中,set方法和out方法持有的锁是this,是同一个锁,那么当set方法出现等待时,因为持有this锁,out方法是无法运行的,那么程序也就死了.
//可是事实是一个等待另一个就运行,为什么呢?
|