V
-可交换的对象的类型
public class Exchanger<V> extends Object
exchange
方法提出了一些目标,与合作伙伴的线匹配,并接收其伴侣的对象返回。交换机可以被看作是一个双向的
SynchronousQueue
形式。交换器等应用遗传算法和管道的设计是有用的。
示例用法:这里是一个类使用一个Exchanger
交换缓冲区之间的螺纹,螺纹填充缓冲区获取一个刚倒一的时候需要它的亮点,把填充一个线程清空缓冲区。
class FillAndEmpty {
Exchanger<DataBuffer> exchanger = new Exchanger<DataBuffer>();
DataBuffer initialEmptyBuffer = ... a made-up type
DataBuffer initialFullBuffer = ...
class FillingLoop implements Runnable {
public void run() {
DataBuffer currentBuffer = initialEmptyBuffer;
try {
while (currentBuffer != null) {
addToBuffer(currentBuffer);
if (currentBuffer.isFull())
currentBuffer = exchanger.exchange(currentBuffer);
}
} catch (InterruptedException ex) { ... handle ... }
}
}
class EmptyingLoop implements Runnable {
public void run() {
DataBuffer currentBuffer = initialFullBuffer;
try {
while (currentBuffer != null) {
takeFromBuffer(currentBuffer);
if (currentBuffer.isEmpty())
currentBuffer = exchanger.exchange(currentBuffer);
}
} catch (InterruptedException ex) { ... handle ...}
}
}
void start() {
new Thread(new FillingLoop()).start();
new Thread(new EmptyingLoop()).start();
}
}
内存一致性效果:对每个线程成功交换对象通过一个Exchanger
,行动之前的exchange()
每个线程happen-before那些从其他线程对应的exchange()
返回后续。
public V exchange(V x) throws InterruptedException
如果另一个线程已经在交换点等待,那么它被恢复为线程调度的目的,并接收通过当前线程传递的对象。当前线程立即返回,接收通过该其他线程传递给该对象的对象。
如果没有其他线程已经在交换中等待,那么当前线程被禁用的线程调度的目的,并处于休眠状态,直到两个事情发生:
如果当前线程:
InterruptedException
投入和当前线程的中断状态被清除。
x
-交换的对象
InterruptedException
-如果当前线程被中断等待
public V exchange(V x, long timeout, TimeUnit unit) throws InterruptedException, TimeoutException
如果另一个线程已经在交换点等待,那么它被恢复为线程调度的目的,并接收通过当前线程传递的对象。当前线程立即返回,接收通过该其他线程传递给该对象的对象。
如果没有其他线程已经在交换中等待,那么当前线程被禁用的线程调度的目的,并处于休眠状态,直到三个事情发生:
如果当前线程:
InterruptedException
投入和当前线程的中断状态被清除。
如果指定的等待时间的流逝,然后TimeoutException
抛出。如果时间小于或等于零,该方法将不会等待在所有。
x
-交换的对象
timeout
-最大等待时间
unit
的
timeout
争论的时间单位
InterruptedException
-如果当前线程被中断等待
TimeoutException
-如果指定的等待时间的流逝,另一个线程进入交换之前
Submit a bug or feature
For further API reference and developer documentation, see Java SE Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.
Copyright © 1993, 2014, Oracle and/or its affiliates. All rights reserved.