java.util.concurrent基础类解析

类图

java.util.concurrent.locks.Condition

{@code Condition} factors out the {@code Object} methods ({@link Object#wait() wait}, {@link Object#notify notify} and {@link Object#notifyAll notifyAll}) into distinct objects to give the effect of having multiple wait-sets per object, by combining them with the use of arbitrary {@link Lock} implementations. Where a {@code Lock} replaces the use of {@code synchronized} methods and statements, a {@code Condition} replaces the use of the Object monitor methods.
Condition使Object#wait()、Object#notify、Object#notifyAll可以对wait-sets生效,通过使用任意Lock的实现。Lock替代了synchronized的使用,Condition提到了对象管程方法的使用。

Conditions (also known as condition queues or condition variables) provide a means for one thread to suspend execution (to "wait") until notified by another thread that some state condition may now be true. Because access to this shared state information occurs in different threads, it must be protected, so a lock of some form is associated with the condition. The key property that waiting for a condition provides is that it atomically releases the associated lock and suspends the current thread, just like {@code Object.wait}.
Condition(条件队列或者条件变量)提供了一种暂定线程执行的方式,这种方式是在其他线程通知之前达到某种状态。因为访问共享状态的行为是在不同线程中发生的,该行为必须被保护,所以某种形式的锁必须和条件关联起来。等待一个条件的关键属性是,原子性的释放相关锁和暂停当前线层,类似Object.wait。

A {@code Condition} instance is intrinsically bound to a lock. To obtain a {@code Condition} instance for a particular {@link Lock} instance use its {@link Lock#newCondition newCondition()} method.
Condition实例和一个锁强绑定。使用Lock#newCondition来获取锁的条件实例。

As an example, suppose we have a bounded buffer which supports {@code put} and {@code take} methods. If a {@code take} is attempted on an empty buffer, then the thread will block until an item becomes available; if a {@code put} is attempted on a full buffer, then the thread will block until a space becomes available. We would like to keep waiting {@code put} threads and {@code take} threads in separate wait-sets so that we can use the optimization of only notifying a single thread at a time when items or spaces become available in the buffer. This can be achieved using two {@link Condition} instances.
例如,假如我们有一个支持put和take的有界buffer。如果尝试对空buffer执行take,线程会阻塞知道buffer有数据。如果尝试对满buffer执行put,线程会阻塞直到有空间可用。我们希望等待put的线程和等待take的线程在不同的wait-sets,所以我们使用优化,当buffer中元素或者空间可用时,一次只通知一个线程。可以使用Condition实例来达到上述效果。

(The {@link java.util.concurrent.ArrayBlockingQueue} class provides this functionality, so there is no reason to implement this sample usage class.)
java.util.concurrent.ArrayBlockingQueue提供了该功能,无需实现案例类。

你可能感兴趣的:(java.util.concurrent基础类解析)