Home > Java > javaTutorial > body text

Interface Condition

巴扎黑
Release: 2017-06-26 11:26:57
Original
1231 people have browsed it

java.util.concurrent.locks Interface Condition

  • All known implementation classes:

  • AbstractQueuedLongSynchronizer. ConditionObject, AbstractQueuedSynchronizer.ConditionObject

##
public interface Condition
Copy after login
<br>
Copy after login

Condition will Object monitor method (wait, notify and notifyAll) are decomposed into distinct objects so that these objects can be combined with any Lock Implement combined use to provide multiple wait sets (wait-set) for each object. Among them, Lock replaces the use of synchronized methods and statements, and Condition replaces the use of Object monitor methods.

Conditions (also called

Condition Queue or Condition Variable) provide a meaning to a thread so that in a certain state a condition may now be true for another thread The thread is suspended (that is, made to "wait") until it is notified. Because access to this shared state information occurs in a different thread, it must be protected, so some form of lock is associated with the condition. The main properties of a wait provided a condition are: Atomicly releases the associated lock and suspends the current thread, just like Object.wait does.

Condition The instance is essentially bound to a lock. To obtain a Condition instance for a specific Lock instance, use its newCondition() method.

As an example, assume there is a bound buffer that supports the

put and take methods. If you attempt to perform a take operation on an empty buffer, the thread will block until an item becomes available; if you attempt to perform a put operation on a full buffer, the thread will block until an item becomes available. , the thread will block until space becomes available. We like to keep the put threads and the take threads in separate wait sets so that we can take advantage of optimal planning when an item or space in the buffer becomes available, notifying only at a time a thread. This can be done using two Condition instances.

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

   final Object[] items = new Object[100];
   int putptr, takeptr, count;

   public void put(Object x) throws InterruptedException {     lock.lock();
     try {   while (count == items.length) 
         notFull.await();   items[putptr] = x; 
       if (++putptr == items.length) putptr = 0;
       ++count;       notEmpty.signal(); } finally {
       lock.unlock();
     }
   }

   public Object take() throws InterruptedException {     lock.lock();
     try {   while (count == 0) 
         notEmpty.await();   Object x = items[takeptr]; 
       if (++takeptr == items.length) takeptr = 0;
       --count;       notFull.signal();   return x;     } finally {
       lock.unlock();
     }
   } 
 }
Copy after login
(The

ArrayBlockingQueue class provides this functionality, so there is no reason to implement this example class.)

Condition An implementation can provide a different Object Behavior and semantics of monitor methods, such as guaranteed ordering of notifications, or the need to hold a lock while executing notifications. If an implementation provides such special semantics, the implementation MUST document these semantics.

Note that

Condition instances are just ordinary objects that themselves can be used as targets in synchronized statements and can call their own wait and notification monitor methods. Obtain the monitor lock of the Condition instance or use its monitor method, and obtain the Lock associated with the Condition or use its waiting It has no specific relationship with the signalling method. To avoid confusion, it is recommended that a Condition instance should never be used in this way except within its own implementation.

Unless otherwise noted, passing a

null value for any parameter will cause a NullPointerException to be thrown.

Implementation Notes

While waiting for a

Condition, "False wakeup" is allowed to occur, usually as a concession to the underlying platform semantics. For most applications, this will have little practical impact, since Condition should always be waited on in a loop, testing the state statement being waited on. An implementation is free to remove possible spurious wakeups, but application programmers are advised to always assume that these spurious wakeups may occur and therefore always wait in a loop.

The implementation of the three forms of conditional waiting (interruptible, uninterruptible, and timeout) on some platforms and their performance characteristics may vary. In particular it can be difficult to provide these features and maintain specific semantics, such as ordering guarantees. Further

, the ability to interrupt a thread from actually suspending is not always possible on all platforms.

Therefore, an implementation is not required to define exactly the same guarantees or semantics for all three forms of wait, nor is it required to support actual suspending of interrupt threads.

Implementations are required to clearly document the semantics and guarantees provided by each wait method. When an implementation does not support the suspension of interrupt threads, it must comply with the interrupt semantics defined in this interface.

Because interrupts usually mean cancellation, and interrupt checks are usually rarely performed, implementations can respond to interrupts before returning from ordinary methods. This is true even when an interrupt that occurs after another operation might release the thread lock. Implementations should document this behavior.

  • Starting with:

  • 1.5


<br>

## boolean(long time , TimeUnit unit) Causes the current thread to wait until it receives the signal. ##awaitUntil(Date deadline )() Wake up all waiting threads.
##Method Summary<strong></strong>
void ##await()<strong> </strong>## Waiting state until interrupted. <br>
##await <strong> Causes the current thread to remain in a waiting state until it receives a signal, is interrupted, or reaches the specified waiting time. </strong><br>## long
##awaitNanos(long nanosTimeout ) Causes the current thread to remain in a waiting state until it receives a signal, is interrupted, or reaches the specified waiting time. <strong></strong><br>## void
##awaitUninterruptibly() <strong></strong>## boolean<br>
Causes the current thread to wait until it receives a signal, is interrupted, or reaches the specified deadline. <strong>## void</strong><br>##signal
Wake up a waiting thread. ## void<strong></strong><br>##signalAll()
<strong></strong><br>##Method details information

<br>

await

void await()
           throws InterruptedException
Copy after login
  • 造成当前线程在接到信号或被中断之前一直处于等待状态。

    与此 Condition 相关的锁以原子方式释放,并且出于线程调度的目的,将禁用当前线程,且在发生以下四种情况之一 以前,当前线程将一直处于休眠状态:

    • 其他某个线程调用此 Conditionsignal() 方法,并且碰巧将当前线程选为被唤醒的线程;或者

    • 其他某个线程调用此 ConditionsignalAll() 方法;或者

    • 其他某个线程中断当前线程,且支持中断线程的挂起;或者

    • 发生“虚假唤醒

    在所有情况下,在此方法可以返回当前线程之前,都必须重新获取与此条件有关的锁。在线程返回时,可以保证 它保持此锁。

    如果当前线程:

    • 在进入此方法时已经设置了该线程的中断状态;或者

    • 在支持等待和中断线程挂起时,线程被中断,

    则抛出 InterruptedException,并清除当前线程的中断状态。在第一种情况下,没有指定是否在释放锁之前发生中断测试。

    实现注意事项

    假定调用此方法时,当前线程保持了与此 Condition 有关联的锁。这取决于确定是否为这种情况以及不是时,如何对此作出响应的实现。通常,将抛出一个异常(比如 IllegalMonitorStateException)并且该实现必须对此进行记录。

    与响应某个信号而返回的普通方法相比,实现可能更喜欢响应某个中断。在这种情况下,实现必须确保信号被重定向到另一个等待线程(如果有的话)。

     

     

    • 抛出:

    • InterruptedException - 如果当前线程被中断(并且支持中断线程挂起)


<br>

awaitUninterruptibly

void awaitUninterruptibly()
Copy after login
  • 造成当前线程在接到信号之前一直处于等待状态。

    与此条件相关的锁以原子方式释放,并且出于线程调度的目的,将禁用当前线程,且在发生以下三种情况之一 以前,当前线程将一直处于休眠状态:

    • 其他某个线程调用此 Conditionsignal() 方法,并且碰巧将当前线程选为被唤醒的线程;或者

    • 其他某个线程调用此 ConditionsignalAll() 方法;或者

    • 发生“虚假唤醒

    在所有情况下,在此方法可以返回当前线程之前,都必须重新获取与此条件有关的锁。在线程返回时,可以保证 它保持此锁。

    如果在进入此方法时设置了当前线程的中断状态,或者在等待时,线程被中断,那么在接到信号之前,它将继续等待。当最终从此方法返回时,仍然将设置其中断状态。

    实现注意事项

    假定调用此方法时,当前线程保持了与此 Condition 有关联的锁。这取决于确定是否为这种情况以及不是时,如何对此作出响应的实现。通常,将抛出一个异常(比如 IllegalMonitorStateException)并且该实现必须对此进行记录。

     


<br>

awaitNanos

long awaitNanos(long nanosTimeout)
                throws InterruptedException
Copy after login
  • 造成当前线程在接到信号、被中断或到达指定等待时间之前一直处于等待状态。

    与此条件相关的锁以原子方式释放,并且出于线程调度的目的,将禁用当前线程,且在发生以下五种情况之一 以前,当前线程将一直处于休眠状态:

    • 其他某个线程调用此 Conditionsignal() 方法,并且碰巧将当前线程选为被唤醒的线程;或者

    • 其他某个线程调用此 ConditionsignalAll() 方法;或者

    • 其他某个线程中断当前线程,且支持中断线程的挂起;或者

    • 已超过指定的等待时间;或者

    • 发生“虚假唤醒”。

    在所有情况下,在此方法可以返回当前线程之前,都必须重新获取与此条件有关的锁。在线程返回时,可以保证 它保持此锁。

    如果当前线程:

    • 在进入此方法时已经设置了该线程的中断状态;或者

    • 在支持等待和中断线程挂起时,线程被中断,

    则抛出 InterruptedException,并且清除当前线程的已中断状态。在第一种情况下,没有指定是否在释放锁之前发生中断测试。

    在返回时,该方法返回了所剩毫微秒数的一个估计值,以等待所提供的 nanosTimeout 值的时间,如果超时,则返回一个小于等于 0 的值。可以用此值来确定在等待返回但某一等待条件仍不具备的情况下,是否要再次等待,以及再次等待的时间。此方法的典型用法采用以下形式:

     synchronized boolean aMethod(long timeout, TimeUnit unit) {
       long nanosTimeout = unit.toNanos(timeout);
       while (!conditionBeingWaitedFor) {
         if (nanosTimeout > 0)
             nanosTimeout = theCondition.awaitNanos(nanosTimeout);
          else
            return false;
       }
       // ... 
     }
    Copy after login

    设计注意事项:此方法需要一个 nanosecond 参数,以避免在报告剩余时间时出现截断错误。在发生重新等待时,这种精度损失使得程序员难以确保总的等待时间不少于指定等待时间。

    实现注意事项

    假定调用此方法时,当前线程保持了与此 Condition 有关联的锁。这取决于确定是否为这种情况以及不是时,如何对此作出响应的实现。通常会抛出一个异常(比如 IllegalMonitorStateException)并且该实现必须对此进行记录。

    与响应某个信号而返回的普通方法相比,或者与指示所使用的指定等待时间相比,实现可能更喜欢响应某个中断。在任意一种情况下,实现必须确保信号被重定向到另一个等待线程(如果有的话)。

     

     

    • 参数:

    • nanosTimeout - 等待的最长时间,以毫微秒为单位

    • 返回:

    • nanosTimeout 值减去花费在等待此方法的返回结果的时间的估算。正值可以用作对此方法进行后续调用的参数,来完成等待所需时间结束。小于等于零的值表示没有剩余时间。

    • 抛出:

    • InterruptedException - 如果当前线程被中断(并且支持中断线程挂起)


<br>

await

boolean await(long time,
              TimeUnit unit)
              throws InterruptedException
Copy after login
  • 造成当前线程在接到信号、被中断或到达指定等待时间之前一直处于等待状态。此方法在行为上等效于:

       awaitNanos(unit.toNanos(time)) > 0
    Copy after login

     

    • 参数:

    • time - 最长等待时间

    • unit - time 参数的时间单位

    • 返回:

    • 如果在从此方法返回前检测到等待时间超时,则返回 false,否则返回 true

    • 抛出:

    • InterruptedException - 如果当前线程被中断(并且支持中断线程挂起)


<br>

awaitUntil

boolean awaitUntil(Date deadline)
                   throws InterruptedException
Copy after login
  • 造成当前线程在接到信号、被中断或到达指定最后期限之前一直处于等待状态。

    与此条件相关的锁以原子方式释放,并且出于线程调度的目的,将禁用当前线程,且在发生以下五种情况之一 以前,当前线程将一直处于休眠状态:

    • 其他某个线程调用此 Conditionsignal() 方法,并且碰巧将当前线程选为被唤醒的线程;或者

    • 其他某个线程调用此 ConditionsignalAll() 方法;或者

    • 其他某个线程中断当前线程,且支持中断线程的挂起;或者

    • 指定的最后期限到了;或者

    • 发生“虚假唤醒”。

    在所有情况下,在此方法可以返回当前线程之前,都必须重新获取与此条件有关的锁。在线程返回时,可以保证 它保持此锁。

    如果当前线程:

    • 在进入此方法时已经设置了该线程的中断状态;或者

    • 在支持等待和中断线程挂起时,线程被中断,

    则抛出 InterruptedException,并且清除当前线程的已中断状态。在第一种情况下,没有指定是否在释放锁之前发生中断测试。

    返回值指示是否到达最后期限,使用方式如下:

     synchronized boolean aMethod(Date deadline) {
       boolean stillWaiting = true;
       while (!conditionBeingWaitedFor) {
         if (stillWaiting)
             stillWaiting = theCondition.awaitUntil(deadline);
          else
            return false;
       }
       // ... 
     }
    Copy after login

    实现注意事项

    假定调用此方法时,当前线程保持了与此 Condition 有关联的锁。这取决于确定是否为这种情况以及不是时,如何对此作出响应的实现。通常,将抛出一个异常(比如 IllegalMonitorStateException)并且该实现必须对此进行记录。

    与响应某个信号而返回的普通方法相比,或者与指示是否到达指定最终期限相比,实现可能更喜欢响应某个中断。在任意一种情况下,实现必须确保信号被重定向到另一个等待线程(如果有的话)。

     

     

    • 参数:

    • deadline - 一直处于等待状态的绝对时间

    • 返回:

    • 如果在返回时已经到达最后期限,则返回 false,否则返回 true

    • 抛出:

    • InterruptedException - 如果当前线程被中断(并且支持中断线程挂起)


<br>

signal

void signal()
Copy after login
  • 唤醒一个等待线程。

    如果所有的线程都在等待此条件,则选择其中的一个唤醒。在从 await 返回之前,该线程必须重新获取锁。

     


<br>

signalAll

void signalAll()
Copy after login
  • 唤醒所有等待线程。

    如果所有的线程都在等待此条件,则唤醒所有线程。在从 await 返回之前,每个线程都必须重新获取锁。

The above is the detailed content of Interface Condition. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template