一、对于wait()和notify()的解释
void notify()
Wakes up a single thread that is waiting on this object’s monitor.
唤醒等待获取锁资源的单个线程
void notifyAll()
Wakes up all threads that are waiting on this object’s monitor.
唤醒等待获取锁资源的所有线程
void wait( )
Causes the current thread to wait until another thread invokes the notify() method or the notifyAll( ) method for this object.
释放出对象的锁资源,程序会阻塞在这里
二、使用wait()、notify()、notifyAll()应该要注意的地方
1、wait( ),notify( ),notifyAll( )都不属于Thread类,属于Object基础类,每个对象都有wait( ),notify( ),notifyAll( ) 的功能,因为每个对象都有锁
2、当需要调用wait( ),notify( ),notifyAll( )的时候,一定都要在synchronized里面,不然会报 IllegalMonitorStateException 异常,可以这样理解,在synchronized(object) {}里面的代码才能获取到对象的锁。
3、while循环里而不是if语句下使用wait,这样,会在线程暂停恢复后都检查wait的条件,并在条件实际上并未改变的情况下处理唤醒通知
4、调用obj.wait( )释放了obj的锁,程序就会阻塞在这里,如果后面被notify()或者notifyAll()方法呼唤醒了之后,那么程序会接着调用obj.wait()后面的程序。
5、notify()唤醒等待获取锁资源的单个线程,notifyAll( )唤醒等待获取锁资源的所有线程
6、当调用obj.notify/notifyAll后,调用线程依旧持有obj锁,其它线程仍无法获得obj锁,直到调用线程退出synchronized块或者在原有的obj调用wait释放锁,其它的线程才能起来
三、使用wait()、notify()、notifyAll()实现非阻塞式的消费者和生产者
package wait;
import java.util.PriorityQueue;
public class WaitAndNofityTest {
public static final int COUNT = 5;
//优先队列,消费者在这个队列里面消耗数据,生产者在这个里面生产数据
public PriorityQueue<Integer> queue = new PriorityQueue<Integer>(COUNT);
public static void main(String[] args) {
WaitAndNofityTest waitAndNofityTest = new WaitAndNofityTest();
Cus cus = waitAndNofityTest.new Cus();
Make make = waitAndNofityTest.new Make();
make.start();
cus.start();
}
//消费者线程类
class Cus extends Thread {
java之wait()、notify()实现非阻塞的生产者和消费者
最新推荐文章于 2022-08-02 14:22:37 发布