wait(),notify()和notifyAll()都是java.lang.Object的方法:
wait(): Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object.
notify(): Wakes up a single thread that is waiting on this object's monitor.
notifyAll(): Wakes up all threads that are waiting on this object's monitor.
这三个方法,都是Java语言提供的实现线程间阻塞(Blocking)和控制进程内调度(inter-process communication)的底层机制。
1.使用条件 --获得锁
在调用wait(), notify()或notifyAll()的时候,必须先获得锁,且状态变量须由该锁保护
如:synchronized (xxxx) {
xxxx.wait();
}
不加锁使用这些方法会出现IllegalMonitorStateException异常.
原因: 在对某个对象上调用wait().notify 等方法进行线程等待或者唤醒(让其他竞争执行该代码的线程上锁)时,没有对该对象执行同步操作。
2.待完----

本文详细介绍了Java中wait(), notify() 和 notifyAll() 方法的基本概念及其使用方式。这些方法是Java语言提供的一种底层机制,用于实现线程间的阻塞与进程内调度。文章强调了在调用这些方法前获取锁的重要性,并解释了未加锁情况下可能出现的异常。
842

被折叠的 条评论
为什么被折叠?



