本帖最后由 垂天云 于 2013-9-2 15:50 编辑
- 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(Input.class)
- {
- if(r.flag)
- try{r.wait();}catch(Exception e){}
- if(x==0)
- {
- r.name="mike";
- r.sex="man";
- }
- else
- {
- r.name="丽丽";
- r.sex = "女女女女女";
- }
- x = (x+1)%2;
- r.flag = true;
- r.notify();
- }
- }
- }
- }
- class Output implements Runnable
- {
- private Res r ;
- Output(Res r)
- {
- this.r = r;
- }
- public void run()
- {
- while(true)
- {
- synchronized(Input.class)//毕老师说锁可以为Input.class,可是这个字节码锁不应该是静态才可以的吗,我运行后报错信息见截图。
- {
- if(!r.flag)
- try{r.wait();}catch(Exception e){}
- System.out.println(r.name+"...."+r.sex);
- r.flag = false;
- r.notify();
- }
- }
- }
- }
- class InputOutputDemo
- {
- 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();
- }
- }
复制代码 问题请见代码中的注释:
问题截图:
|
|