Waiting on a condition in a reentrant lock

前端 未结 3 864
無奈伤痛
無奈伤痛 2021-02-01 16:02

The following code is taken from the JavaDoc of Condition:

class BoundedBuffer {
  final Lock lock = new ReentrantLock();
  final Condition notFull  = lock.newCo         


        
3条回答
  •  悲&欢浪女
    2021-02-01 16:51

    Both Lock and synchronized allow a thread to give up the lock when waiting and another thread can obtain the lock. To stop waiting, a thread have to re-acquire the lock.

    Note: They don't release it fully and if you take a stack trace you can have multiple threads which appear to be holding the lock at once, but at most one of them will be running (the rest will be blocking)

    From Condition.await()

    The lock associated with this Condition is atomically released and the current thread becomes disabled for thread scheduling purposes and lies dormant until one of four things happens:

    • Some other thread invokes the signal() method for this Condition and the current thread happens to be chosen as the thread to be awakened; or
    • Some other thread invokes the signalAll() method for this Condition; or
    • Some other thread interrupts the current thread, and interruption of thread suspension is supported; or
    • A "spurious wakeup" occurs.

    In all cases, before this method can return the current thread must re-acquire the lock associated with this condition. When the thread returns it is guaranteed to hold this lock

提交回复
热议问题