preface

  • Traditionally, we can passsynchronizedThe keyword +wait + notify/notifyAllTo achieve coordination and communication between multiple threads, the whole process is helped by the JVM to achieve; Developers do not (and cannot) know the underlying implementation details,One object has onewait set
  • Starting with JDK 5, and shipping packages are providedThe Lock, Condition (await and signal/signalAll)To achieve coordination and communication between multiple threads, the whole process is controlled by the developer, and compared with the traditional way, more flexible, more powerful function,There can be more than one objectwait set

As usual, continue with the documentation to see what the Condition interface does

  • ConditionwillObjecT monitor method (ObjectClass)Wait, notify,andnotifyAlldecompositionFor different objects, by associating them with anyLockUse of implementationCombine (bind)Generates each object withThere are multiple wait setsThe effect.Lock replaces the use of synchronized methods and statements, and Condition replaces the use of object monitor methods.
    • aboutAn object has multiple wait setsWhat are the benefits?
  • Condition(also known as conditional queues or conditional variables) provides a way for one thread to suspend execution (” wait “) until another thread informs that a status condition may now betrue. Because access to this shared state information occurs in different threads, itMust be protected.So some form of Lock is associated with Condition (binding). Waiting for theConditioThe key property provided by n is that it automatically releases the associated lock and suspends the current thread, as inObject.waiT the same.
  • ConditionInstances are objectively bound to locks. To get the Condition instance of a particular Lock instance, use itnewCondition()Methods.

  • ConditionImplementations can be provided withObjectMonitor methoddifferentBehavior and semantics, such as ensuring the order of notifications, or not requiring locks to be held when notifications are executed. If the implementation provides such specialized semantics, then the implementation must document those semantics.
  • Please note that,ConditionInstances are just ordinary objectsThey themselves can be used assynchronizedStatement, and can invoke their own monitorswaitandnotificationMethods. To obtainConditionInstance of the monitor lock, or use its monitor method, with the acquisition associated with theConditionThe associatedLockOr its waiting (await) and signal (signalThere is no specific relationship between the use of methods.It is recommended that you do not use Condition instances in this way to avoid confusionExcept in their own implementation.
  • Pass for any parameter unless otherwise statednullValues will result in a throwNullPointerException

Introduces methods in Condition

void await() throws InterruptedException;

  • Causes the current thread to wait until it receives a signal or is interrupted.
  • With thisLockThe relevantConditionThe lock is automatically released, and the current thread is used for thread scheduling purposes, disabled and remains dormant until one of the following four events occurs:
    • Some other thread does thisConditionCall thesignalMethod, and happens to select the current thread as the thread to wake up; or
    • Some other threads do thisConditioncallsignalAllMethods; or
    • Other threads interrupt the current thread, supporting thread suspension interrupts; or
    • False wake up occurs. (Woke up without being notified by another thread)
  • In all cases, the lock associated with this condition must be reacquired before this method can return to the current thread. When the thread returns, it is guaranteed to hold the lock.
  • If the current thread:
    • Set the middle off state when entering this method; or
    • Interrupt while waiting, support thread suspend interrupt,

    Then throwInterruptedExceptionAnd clears the interrupted state of the current thread. In the first case, whether an interrupt test is performed before the lock is releasedThere’s no rule.

void awaitUninterruptibly();

  • With the aboveawaitThe same
  • One too many reads:

  • If the current thread is set to interrupt when entering the method, or is interrupted while waiting, it will continue to wait until it receives a signal. When it finally returns from this method, its broken state is still there. (In short, uninterruptible)

long awaitNanos(long nanosTimeout) throws InterruptedException;

  • Note that the return value islong

  • Causes the current thread to wait until it receives a signal or is interrupted, or the specified wait time has elapsed.
  • The lock associated with this Condition is automatically released, and the current thread is disabled and dormant for thread scheduling purposes until one of the following five things happens:
    • Some other thread does thisConditionCall thesignalMethod, and happens to select the current thread as the thread to wake up; or
    • Some other threads do thisConditioncallsignalAllMethods; or
    • Other threads interrupt the current thread, thread suspension interrupts are supported; or
    • The specified wait time has elapsed. or
    • False wake up occurs.
  • In all cases, the lock associated with this condition must be reacquired before this method can return to the current thread. When the thread returns, it is guaranteed to hold the lock.
  • If the current thread:
    • Set the middle off state when entering this method; or
    • Interrupt while waiting, support thread suspend interrupt,

    Then throwInterruptedExceptionAnd clears the interrupted state of the current thread. In the first case, it is not specified whether an interrupt test is performed before the lock is released.

  • Provided when given a returnnanosTimeoutValue, which returns an estimate of the number of nanoseconds remaining to wait (parameter minus the number of seconds to be awakened),If the timeoutReturns a value less than or equal to 0 (there is an error, after all, but not much less than 0).This value can be used to determine whether and for how long to wait again if the wait returns but the wait condition remains untenable.

Parameters: nanosTimeout – Maximum wait time in nanoseconds Return value: nanosTimeout value minus an estimate of the time spent waiting to return from the method. You can use positive values as arguments to subsequent calls to the method to complete the wait. A value less than or equal to zero indicates no time left. Throws: InterruptedException – if the current thread is interrupted (and thread suspension interruption is supported)

boolean await(long time, TimeUnit unit) throws InterruptedException;

  • Causes the current thread to wait until it is signaled or interrupted, or the specified wait time has elapsed. This method is behaviorally equivalent to: awaitNanos(unit.tonanos (time)) > 0

Parameter: time – maximum time to wait unit-time Unit of time for the parameter Return value: false if the wait time has passed can be detected before returning from the method, otherwise true Throws: InterruptedException – If the current thread is interrupted (and thread suspension interruption is supported)

boolean awaitUntil(Date deadline) throws InterruptedException;

  • Similar to Boolean await(long time, TimeUnit unit)

Return value: false if the deadline has passed, true otherwise

void signal();

  • Wake up a waiting thread.
  • If there are any threads waiting on the condition, a thread is selected to wake up. The awakened thread must reacquire the lock before returning from await (await end).

void signalAll();

  • Wake up all waiting threads.
  • If any threads are waiting for this, they will be woken up. Each thread must reacquire the lock to return from the await