本帖最后由 java小兵 于 2015-1-26 21:35 编辑
- class Res
- {
- String name;
- String sex;
- boolean flag = false;
- }
- class Input implements Runnable
- {
- private Res r;
- Input(Res r)
- {
- this.r = r;
- }
- public void run()
- {
- int x = 0;
- while (true)
- {
- synchronized(r)
- {
- if(r.flag)
- try{r.wait();}catch(Exception e){}
-
- if (x==0)
- {
-
- r.name = "mike";
- r.sex = "man";
-
- }
- else
- {
- r.name = "Lucy";
- r.sex = "woman";
- }
- x = (x+1)%2;
- r.flag = true;
- r.notify();
- }
- }
- }
- }
- class Outer implements Runnable
- {
- private Res r;
- Outer(Res r)
- {
- this.r = r;
- }
- public void run()
- {
- while (true)
- {
- synchronized(r)
- {
- if(!r.flag)
- try{wait();}catch(Exception e){}
- System.out.println(r.name+"--"+r.sex);
- r.flag = false;
- r.notify();
- }
- }
- }
- }
- class Demo2_3
- {
- public static void main(String[] args)
- {
- Res r = new Res();
- Input in = new Input(r);
- Outer out = new Outer(r);
- Thread t1 = new Thread(in);
- Thread t2 = new Thread(out);
- t1.start();
- t2.start();
- System.out.println("Hello World!");
- }
- }
复制代码
代码是照抄的。结果跟没加wait notify是一样的怎么回事呢? |
|