- class Res
- {
- String name;
- String sex;
- boolean flag = false;
- }
- class Input implements Runnable
- {
- private Res s;
- Input(Res s)
- {
- this.s = s;
- }
- public void run()
- {
- //boolean b = true;
- int x = 0;
- while(true)
- {
- synchronized(Res.class)
- {
- if(s.flag)
- try{Res.class.wait();}catch(Exception e){}
- if(x==0)
- {
- s.name = "Jack";
- s.sex = "man";
- //b=false;
- }
- else
- {
- s.name = "丽丽";
- s.sex = "女";
- //b=true;
- }
- x = (x+1)%2;
- s.flag = true;
- Res.class.notify();
- }
- }
- }
- }
- class Output implements Runnable
- {
- private Res s;
- Output(Res s)
- {
- this.s = s;
- }
- public void run()
- {
-
- while(true)
- {
-
- synchronized(Res.class)
- {
- if(!s.flag)
- try{Res.class.wait();}catch(Exception e){}
- System.out.println(s.name+"...."+s.sex);
- s.flag = true;
- Res.class.notify();
- }
-
- }
- }
- }
- public class InputOutputDemo
- {
- public static void main(String[] args)
- {
- Res s = new Res();
- Input i = new Input(s);
- Output o = new Output(s);
-
- Thread t1 = new Thread(i);
- Thread t2 = new Thread(o);
-
- t1.start();
- t2.start();
- }
- }
复制代码 //照着毕老师的一点点自己打的。结果又不对。愁啊。。求帮忙看看 |