黑马程序员技术交流社区

标题: 求助。 [打印本页]

作者: 李有    时间: 2012-11-22 16:20
标题: 求助。
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 ,y = 1;
                while(y++<=50000){
                        synchronized(r){
                                if(r.flag)
                                        try{r.wait();}
                                catch(Exception e){}
                if(x==0){
                r.name = "Tom";
                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(){
                int y = 1;
                while(y++<=50000){
                        synchronized(r){
                                if(!r.flag)
                                        try{r.wait();}
                                catch(Exception e){}
                System.out.println(r.name+"......"+r.sex);
                r.flag = false;
                r.notify();
                        }
                }
        }
}
public class InOutPutDemo {

        public static void main(String[] args) {
  
       Res r = new Res();
       new Thread(new InPut(r)).start();
       new Thread(new OutPut(r)).start();
               
        }

}


程序抛出java.lang.IllegalMonitorStateException异常,说明:当前线程不是此对象监视器的所有者;该如何解决?
为什么老毕视频中使用同一锁r的wait()、notify()是可以的呢?
作者: 王阳    时间: 2012-11-23 20:54
public void run(){
                int x = 0 ,y = 1;
                while(y++<=50000){
                        synchronized(r){
                                if(r.flag)
                                        try{r.wait();}
                                catch(Exception e){}
                if(x==0){
                r.name = "Tom";
                r.sex = "Man";
                }
                else{
                            r.name = "丽丽";
                    r.sex = "女孩女孩";
                }
                        }
                x = (x+1)%2;
                r.flag = true;
                r.notify();

        }
标红色的代码也应该在同步内,不然的话就会报你那个异常,因为唤醒的时候不早知道是哪个线程
作者: filter    时间: 2012-11-23 22:42
很好,学写了




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2