- package cn.javastudy.demo1;
- class Res
- {
- String name;
- String sex;
- boolean flag = false;
- }
- /*
- Input线程负责
- 向资源对象中存放数据
- */
- class Input implements Runnable
- {
- private Res r ;
- Object obj = new Object();
- 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 = "male";
- x = 1;
- }else{
- r.name = "丽丽";
- r.sex = "女女女女女";
- x = 0;
- }
- r.flag = true ;
- r.notify();
- }
- }
- }
- }
- /*
- Output此线程负责
- 从资源对象中取出数据并打印
- */
- class Output implements Runnable
- {
- private Res r ;
- Output(Res r)
- {
- this.r = r;
- }
- public void run()
- {
- while(true)
- {
- synchronized(r)
- {
- 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)
- {
- //创建资源对象 Input和Output线程共享此资源
- Res r = new Res();
-
- Input in = new Input(r);
- Output out = new Output(r);
- //创建线程t1和t2 并分别启动
- Thread t1 = new Thread(in);
- Thread t2 = new Thread(out);
- t1.start();
- t2.start();
-
- }
- }
复制代码 你的notify()不是对应锁的监视器,而是this的监视器,所以会发生错误.我给你的这段代码才是正确的,应该用r.notify(),因为你的锁是r对象,且你用r的wait() |