为了账号安全,请及时绑定邮箱和手机立即绑定

Java异常之IllegalMonitorStateException

标签:
Java

JavaDoc

Thrown to indicate that a thread has attempted to wait on an object's monitor or to notify other threads waiting on an object's monitor without owning the specified monitor.
其实意思就是说,也就是当前的线程不是此对象监视器的所有者。也就是要在当前线程锁定对象,才能用锁定的对象此行这些方法,需要用到synchronized ,锁定什么对象就用什么对象来执行  notify(), notifyAll(),wait(), wait(long), wait(long, int)操作,否则就会报IllegalMonitorStateException

A thread becomes the owner of the object's monitor in one of three ways:
1. By executing a synchronized instance method of that object.
2. By executing the body of a synchronized statement that synchronizes on the object.
3. For objects of type Class, by executing a synchronized static method of that class.
通过以下三种方法之一,线程可以成为此对象监视器的所有者:

  • 执行此对象的同步 (Sychronized) 实例方法

  • 执行在此对象上进行同步的 synchronized 语句的正文

  • 对于 Class 类型的对象,执行该类的同步静态方法

也就是在说,就是需要在调用wait()或者notify()之前,必须使用synchronized语义绑定住被wait/notify的对象。

解决方法:

通过实现加锁的方式实现线程同步时产生的并发问题

1 锁定方法所属的实例对象

public synchronized void method(){    //然后就可以调用:this.notify()...
    //或者直接调用notify()...}

2 锁定方法所属的实例的Class

public Class Test{ public static synchronized void method(){    //然后调用:Test.class.notify()...
 }
}

3 锁定其他对象

public Class Test{public Object lock = new Object(); public static void method(){    synchronized (lock) {     //需要调用 lock.notify();
    } 
 }
}

总结

线程操作的wait()、notify()、notifyAll()只能在同步控制方法或同步控制块内调用
如果在非同步控制方法或控制块里调用,程序能通过编译,但运行的时候,将得到  IllegalMonitorStateException 异常,并伴随着一些含糊信息,比如 ‘当前线程不是拥有者’。
其实异常的含义是 调用wait()、notify()、notifyAll()的任务在调用这些方法前必须 ‘拥有’(获取)对象的锁。”



作者:芥末无疆sss
链接:https://www.jianshu.com/p/dd17ce07a6d4
來源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。


点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消