本质上就是: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 类型的对象,可以通过执行该类的同步静态方法。
========================================================================
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