java之wait()、notify()实现非阻塞的生产者和消费者

一、对于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 {

更多请见:http://www.mark-to-win.com/tutorial/51787.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值