Java多线程学习之wait(),notify(),notifyAll()
使用介绍
1.wait()使当前线程线程进去等待状态(注意不是阻塞状态),前提是在这个线程持有锁的情况下。否者会抛出异常java.lang.IllegalMonitorStateException: object not locked by thread before wait()。一般是和synchronized搭配使用,执行wait()后会释放当前线程的锁(并不一定是wait()方法的调用者),等待被notify()或者notifyAll()唤醒。
2.只有当notify()/notifyAll()被执行的时候,才会唤醒一个或多个处于等待状态的线程,被唤醒的线程会在上一次等待的位置继续向下执行。
3.时序上肯定是,先wait()后notify(),且两个方法的调用者肯定是一致的,不然不会生效
样例:使用wait(),notify()和非阻塞队列PriorityQueue来实现生产者消费者
摘自《Android进阶之光》
private final String TAG = "0127生产者"; private final String TBG = "0127消费者"; private int queueSize = 10; private PriorityQueue<Integer> queue = new PriorityQueue<>(queueSize); class Consumer extends Thread{ @Override public void run() { super.run(); while (true){ Log.d(TBG, "目前剩余总数: "+queue.size()); synchronized (queue){ while (queue.size() == 0){ try { Log.d(TAG, "队列空,等待数据"); queue.wait(); } catch (InterruptedException e) { e.printStackTrace(); queue.notify(); } } //每次移走队首元素 queue.poll(); queue.notify(); } } } } class Producer extends Thread{ @Override public void run() { super.run(); while (true){ synchronized (queue){ Log.d(TAG, "目前生产总数: "+queue.size()); while (queue.size() == queueSize){ try { Log.d(TAG, "队列满,等待有空余空间"); queue.wait();//释放锁不在执行 } catch (InterruptedException e) { e.printStackTrace(); queue.notify(); } } queue.offer(1); queue.notify(); } } } } public void run(){ Producer producer = new Producer(); Consumer consumer = new Consumer(); producer.start(); consumer.start(); }
参考资料:https://www.cnblogs.com/moongeek/p/7631447.html

浙公网安备 33010602011771号