• object.wait为什么要和synchronized一块使用


    Object.wait 中JDK提供的doc文档

    Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object. 
    In other words, this method behaves exactly as if it simply performs the call wait(0). The current thread must own this object's monitor.
    The thread releases ownership of this monitor and waits until another thread notifies threads waiting on this object's monitor to wake up
    either through a call to the notify method or the notifyAll method.
    The thread then waits until it can re-obtain ownership of the monitor and resumes execution. As in the one argument version, interrupts and spurious wakeups are possible, and this method should always be used in a loop: synchronized (obj) { while (<condition does not hold>) obj.wait(); ... // Perform action appropriate to condition } This method should only be called by a thread that is the owner of this object's monitor.
    See the notify method for a description of the ways in which a thread can become the owner of a monitor.

      

    一个对象的monitor只能被一个线程占用,wait()方法会释放这个对象的锁, 既然要释放 就先要取得这个锁, 取得对象锁的方式只有synchronized()。释放锁之后, 线程进入BLOCK状态

    doc文档中说明调用wait的时机是因为运行条件condition不满足,

    比如生产者没有往队列中放东西,队列已经空了。队列不为空的时候,再调用obj.notify()。此时condation==队列,obj是针对这个队列的线程间共享变量,也可以是队列本身(最好不是,会阻塞生产者的线程)?

  • 相关阅读:
    Delphi编译器属性(特别修饰符Ref,Unsafe,Volatile,Weak)
    .netcore dapr微服务入门
    Net WebApi一个简单的Token验证
    发布订阅和观察者模式
    NET Core创建Windows服务
    jquery.barrager.js弹幕实现
    跨平台中的RN、Flutter,服务端GraphQL、Serverless,Node和Electron
    分布式系统与高并发高可用
    11 个 Linux 命令
    接口幂等性
  • 原文地址:https://www.cnblogs.com/yszzu/p/9346006.html
Copyright © 2020-2023  润新知