qq_35169059
我最怜君中宵舞
2016-11-11 07:31
采纳率: 75%
浏览 957
已采纳

.IllegalMonitorStateException报错

我有一段这样的代码
Dotry try1=new Dotry("线程1");
Dotry try2=new Dotry("线程2");
try1.start();
try1.join();
Thread.sleep(2000);
try1.wait();
try2.start();
调试后报错我想问一下时怎么回事啊?
class Dotry extends Thread{
String name;
public Dotry(String name){
this.name=name;
}
public void run(){
for(int i=15;i>0;i--){
System.out.println(name+"在运行");
}
}

}

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • caozhy
    已采纳
    点赞 评论
  • wojiushiwo945you
    毕小宝 2016-11-12 08:35

    如果当前线程不是此对象监视器的所有者,就会抛出该异常,也就是说调用wait方法之前,必须先获取该对象的同步监视器。正确的使用语法必须是:

     synchronized(try1){
                    try1.wait();
                }
    

    其实你可以F3看下这个wait方法的源码,API文档的注释是这样的:

          * <pre>
         *     synchronized (obj) {
         *         while (&lt;condition does not hold&gt;)
         *             obj.wait();
         *         ... // Perform action appropriate to condition
         *     }
         * </pre>
         * This method should only be called by a thread that is the owner
         * of this object's monitor. See the {@code notify} method for a
         * description of the ways in which a thread can become the owner of
         * a monitor.
    
    点赞 评论

相关推荐