版权声明:https://blog.csdn.net/Burgess_Lee https://blog.csdn.net/Burgess_Lee/article/details/89631952
基于jdk1.8源码进行分析的。
Exchanger用于两个线程之间交换数据。
继承结构
public class Exchanger<V>
可以简单没有继承什么类,也没实现什么接口。
构造方法
public Exchanger() {
participant = new Participant();
}
构造方法实例化Participant类。
成员方法
exchange(V x)
等待另一个线程到达此交换点(除非当前线程被中断),然后将给定的对象传送给该线程,并接收该线程的对象。
@SuppressWarnings("unchecked")
public V exchange(V x) throws InterruptedException {
Object v;
Object item = (x == null) ? NULL_ITEM : x; // translate null args
if ((arena != null ||
(v = slotExchange(item, false, 0L)) == null) &&
((Thread.interrupted() || // disambiguates null return
(v = arenaExchange(item, false, 0L)) == null)))
throw new InterruptedException();
return (v == NULL_ITEM) ? null : (V)v;
}
如果另一个线程已经在交换点等待,则出于线程调度目的,继续执行此线程,并接收当前线程传入的对象。当前线程立即返回,接收其他线程传递的交换对象。
如果还没有其他线程在交换点等待,则出于调度目的,禁用当前线程,且在发生以下两种情况之一前,该线程将一直处于休眠状态:
- 其他某个线程进入交换点
- 其他某个线程中断当前线程
如果当前线程在进入此方法时已经设置了该线程的中断状态或者 在等待交换时被中断,则抛出 InterruptedException,并且清除当前线程的已中断状态。
exchange(V x, long timeout, TimeUnit unit)
等待另一个线程到达此交换点(除非当前线程被中断,或者超出了指定的等待时间),然后将给定的对象传送给该线程,同时接收该线程的对象。
@SuppressWarnings("unchecked")
public V exchange(V x, long timeout, TimeUnit unit)
throws InterruptedException, TimeoutException {
Object v;
Object item = (x == null) ? NULL_ITEM : x;
long ns = unit.toNanos(timeout);
if ((arena != null ||
(v = slotExchange(item, true, ns)) == null) &&
((Thread.interrupted() ||
(v = arenaExchange(item, true, ns)) == null)))
throw new InterruptedException();
if (v == TIMED_OUT)
throw new TimeoutException();
return (v == NULL_ITEM) ? null : (V)v;
}
上面这么说可能还是太抽象了,下面我们写一个DEMO演示,我们继续往下看。
下次继续。