线程wait和notify报错java.lang.IllegalMonitorStateException

本质上就是:sleep是Thread类的方法,wait是Object类中定义的方法

JavaDoc中说到:

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的对象。

========================================================================

sleep 让线程从 【running】 -> 【阻塞态】 时间结束/interrupt -> 【runnable】
wait 让线程从 【running】 -> 【等待队列】notify -> 【锁池】 -> 【runnable】



代码示例:

exapmle 1,锁定方法所属的实例对象:
public synchronized void method(){
    //然后就可以调用:this.notify()...
    //或者直接调用notify()...
}


exapmle 2,锁定方法所属的实例的Class:
public Class Test{
 public static synchronized void method(){
    //然后调用:Test.class.notify()...
 }
}


exapmle 3,锁定其他对象:
public Class Test{
public Object lock = new Object();
 public static void method(){
    synchronized (lock) {
     //需要调用 lock.notify();
    } 
 }
}


总结:

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


参考:java api

  http://blog.csdn.net/Wen_Demo/article/details/41974623

  http://blog.csdn.net/intlgj/article/details/6245226

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值