---
title: "Java并发编程: 使用Exchanger实现线程间的数据交换"
author: "iaspecwang"
date: "2013-08-25T17:32:53Z"
tags: []
categories: ["企业架构"]
slug: "java-exchanger"
draft: false
lastmod: "2013-08-25T17:32:53Z"
id: 1929703
url: "https://iaspecwang.iteye.com/blog/1929703"
---

本文介绍Exchanger工具类, 然后采用Exchanger给出一个两个线程交换数值的简单实例。 

**1. Exchanger介绍** 

Java代码  [![收藏代码](http://mouselearnjava.iteye.com/images/icon_star.png)]()

1. /\**
2. * A synchronization point at which two threads can exchange objects.
3. * Each thread presents some object on entry to the {@link #exchange
4. * exchange} method, and receives the object presented by the other
5. * thread on return.
6. \*/

从上面的注释中可以看出：Exchanger提供了**一个同步点**，**在这个同步点，两个线程可以交换数据**。每个线程通过exchange()方法的入口提供数据给另外的线程，并接收其它线程提供的数据，并返回。 

Exchanger通过Lock和Condition来完成功能，Exchanger的一个重要的public方法是exchange方法，用于线程的数据交换, 相关的类图以及详细的Exchanger类内容如下： 

![](http://dl2.iteye.com/upload/attachment/0087/9696/0e66dbdb-8304-3417-94cf-5b9c478d57b7.jpg) 

Java代码  [![收藏代码](http://mouselearnjava.iteye.com/images/icon_star.png)]()

001. package java.util.concurrent;
002. import java.util.concurrent.locks.\*;
003. /\**
004. * A synchronization point at which two threads can exchange objects.
005. * Each thread presents some object on entry to the {@link #exchange
006. * exchange} method, and receives the object presented by the other
007. * thread on return.
008. \*
009. * &lt;p&gt;&lt;b&gt;Sample Usage:&lt;/b&gt;
010. * Here are the highlights of a class that uses an &lt;tt&gt;Exchanger&lt;/tt&gt; to
011. * swap buffers between threads so that the thread filling the
012. * buffer gets a freshly
013. * emptied one when it needs it, handing off the filled one to
014. * the thread emptying the buffer.
015. * &lt;pre&gt;
016. * class FillAndEmpty {
017. *   Exchanger&lt;DataBuffer&gt; exchanger = new Exchanger();
018. *   DataBuffer initialEmptyBuffer = ... a made-up type
019. *   DataBuffer initialFullBuffer = ...
020. \*
021. *   class FillingLoop implements Runnable {
022. *     public void run() {
023. *       DataBuffer currentBuffer = initialEmptyBuffer;
024. *       try {
025. *         while (currentBuffer != null) {
026. *           addToBuffer(currentBuffer);
027. *           if (currentBuffer.full())
028. *             currentBuffer = exchanger.exchange(currentBuffer);
029. *         }
030. *       } catch (InterruptedException ex) { ... handle ... }
031. *     }
032. *   }
033. \*
034. *   class EmptyingLoop implements Runnable {
035. *     public void run() {
036. *       DataBuffer currentBuffer = initialFullBuffer;
037. *       try {
038. *         while (currentBuffer != null) {
039. *           takeFromBuffer(currentBuffer);
040. *           if (currentBuffer.empty())
041. *             currentBuffer = exchanger.exchange(currentBuffer);
042. *         }
043. *       } catch (InterruptedException ex) { ... handle ...}
044. *     }
045. *   }
046. \*
047. *   void start() {
048. *     new Thread(new FillingLoop()).start();
049. *     new Thread(new EmptyingLoop()).start();
050. *   }
051. * }
052. * &lt;/pre&gt;
053. \*
054. * @since 1.5
055. * @author Doug Lea
056. * @param &lt;V&gt; The type of objects that may be exchanged
057. \*/
058. public class Exchanger&lt;V&gt; {
059. private final ReentrantLock lock = new ReentrantLock();
060. private final Condition taken = lock.newCondition();
061. /\** Holder for the item being exchanged \*/
062. private V item;
063. /\**
064. * Arrival count transitions from 0 to 1 to 2 then back to 0
065. * during an exchange.
066. \*/
067. private int arrivalCount;
068. /\**
069. * Main exchange function, handling the different policy variants.
070. \*/
071. private V doExchange(V x, boolean timed, long nanos) throws InterruptedException, TimeoutException {
072. lock.lock();
073. try {
074. V other;
075. // If arrival count already at two, we must wait for
076. // a previous pair to finish and reset the count;
077. while (arrivalCount == 2) {
078. if (!timed)
079. taken.await();
080. else if (nanos &gt; 0)
081. nanos = taken.awaitNanos(nanos);
082. else
083. throw new TimeoutException();
084. }
085. int count = ++arrivalCount;
086. // If item is already waiting, replace it and signal other thread
087. if (count == 2) {
088. other = item;
089. item = x;
090. taken.signal();
091. return other;
092. }
093. // Otherwise, set item and wait for another thread to
094. // replace it and signal us.
095. item = x;
096. InterruptedException interrupted = null;
097. try {
098. while (arrivalCount != 2) {
099. if (!timed)
100. taken.await();
101. else if (nanos &gt; 0)
102. nanos = taken.awaitNanos(nanos);
103. else
104. break; // timed out
105. }
106. } catch (InterruptedException ie) {
107. interrupted = ie;
108. }
109. // Get and reset item and count after the wait.
110. // (We need to do this even if wait was aborted.)
111. other = item;
112. item = null;
113. count = arrivalCount;
114. arrivalCount = 0;
115. taken.signal();
116. // If the other thread replaced item, then we must
117. // continue even if cancelled.
118. if (count == 2) {
119. if (interrupted != null)
120. Thread.currentThread().interrupt();
121. return other;
122. }
123. // If no one is waiting for us, we can back out
124. if (interrupted != null)
125. throw interrupted;
126. else  // must be timeout
127. throw new TimeoutException();
128. } finally {
129. lock.unlock();
130. }
131. }
132. /\**
133. * Create a new Exchanger.
134. \*\*/
135. public Exchanger() {
136. }
137. /\**
138. * Waits for another thread to arrive at this exchange point (unless
139. * it is {@link Thread#interrupt interrupted}),
140. * and then transfers the given object to it, receiving its object
141. * in return.
142. * &lt;p&gt;If another thread is already waiting at the exchange point then
143. * it is resumed for thread scheduling purposes and receives the object
144. * passed in by the current thread. The current thread returns immediately,
145. * receiving the object passed to the exchange by that other thread.
146. * &lt;p&gt;If no other thread is already waiting at the exchange then the
147. * current thread is disabled for thread scheduling purposes and lies
148. * dormant until one of two things happens:
149. * \[list]
150. * &lt;li&gt;Some other thread enters the exchange; or
151. * &lt;li&gt;Some other thread {@link Thread#interrupt interrupts} the current
152. * thread.
153. * \[/list]
154. * &lt;p&gt;If the current thread:
155. * \[list]
156. * &lt;li&gt;has its interrupted status set on entry to this method; or
157. * &lt;li&gt;is {@link Thread#interrupt interrupted} while waiting
158. * for the exchange,
159. * \[/list]
160. * then {@link InterruptedException} is thrown and the current thread's
161. * interrupted status is cleared.
162. \*
163. * @param x the object to exchange
164. * @return the object provided by the other thread.
165. * @throws InterruptedException if current thread was interrupted
166. * while waiting
167. \*\*/
168. public V exchange(V x) throws InterruptedException {
169. try {
170. return doExchange(x, false, 0);
171. } catch (TimeoutException cannotHappen) {
172. throw new Error(cannotHappen);
173. }
174. }
175. /\**
176. * Waits for another thread to arrive at this exchange point (unless
177. * it is {@link Thread#interrupt interrupted}, or the specified waiting
178. * time elapses),
179. * and then transfers the given object to it, receiving its object
180. * in return.
181. \*
182. * &lt;p&gt;If another thread is already waiting at the exchange point then
183. * it is resumed for thread scheduling purposes and receives the object
184. * passed in by the current thread. The current thread returns immediately,
185. * receiving the object passed to the exchange by that other thread.
186. \*
187. * &lt;p&gt;If no other thread is already waiting at the exchange then the
188. * current thread is disabled for thread scheduling purposes and lies
189. * dormant until one of three things happens:
190. * \[list]
191. * &lt;li&gt;Some other thread enters the exchange; or
192. * &lt;li&gt;Some other thread {@link Thread#interrupt interrupts} the current
193. * thread; or
194. * &lt;li&gt;The specified waiting time elapses.
195. * \[/list]
196. * &lt;p&gt;If the current thread:
197. * \[list]
198. * &lt;li&gt;has its interrupted status set on entry to this method; or
199. * &lt;li&gt;is {@link Thread#interrupt interrupted} while waiting
200. * for the exchange,
201. * \[/list]
202. * then {@link InterruptedException} is thrown and the current thread's
203. * interrupted status is cleared.
204. \*
205. * &lt;p&gt;If the specified waiting time elapses then {@link TimeoutException}
206. * is thrown.
207. * If the time is
208. * less than or equal to zero, the method will not wait at all.
209. \*
210. * @param x the object to exchange
211. * @param timeout the maximum time to wait
212. * @param unit the time unit of the &lt;tt&gt;timeout&lt;/tt&gt; argument.
213. * @return the object provided by the other thread.
214. * @throws InterruptedException if current thread was interrupted
215. * while waiting
216. * @throws TimeoutException if the specified waiting time elapses before
217. * another thread enters the exchange.
218. \*\*/
219. public V exchange(V x, long timeout, TimeUnit unit)
220. throws InterruptedException, TimeoutException {
221. return doExchange(x, true, unit.toNanos(timeout));
222. }
223. }

**2. Exchanger工具类的使用案例**   
本文给出一个简单的例子，实现两个线程之间交换数据，用Exchanger来做非常简单。 

Java代码  [![收藏代码](http://mouselearnjava.iteye.com/images/icon_star.png)]()

01. package my.concurrent.exchanger;
02. import java.util.concurrent.Exchanger;
03. import java.util.concurrent.atomic.AtomicReference;
04. public class ThreadA implements Runnable {
05. private final Exchanger&lt;Integer&gt; exchanger;
06. private final AtomicReference&lt;Integer&gt; last = new AtomicReference&lt;Integer&gt;(
07. 5);
08. public ThreadA(Exchanger&lt;Integer&gt; exchanger) {
09. this.exchanger = exchanger;
10. }
11. public void run() {
12. try {
13. while (true) {
14. last.set(exchanger.exchange(last.get()));
15. System.out.println(" After calling exchange. Thread A has value: " + last.get());
16. Thread.sleep(2000);
17. }
18. } catch (InterruptedException e) {
19. e.printStackTrace();
20. }
21. }
22. }

Java代码  [![收藏代码](http://mouselearnjava.iteye.com/images/icon_star.png)]()

01. package my.concurrent.exchanger;
02. import java.util.concurrent.Exchanger;
03. import java.util.concurrent.atomic.AtomicReference;
04. public class ThreadB implements Runnable {
05. private Exchanger&lt;Integer&gt; exchanger;
06. private final AtomicReference&lt;Integer&gt; last = new AtomicReference&lt;Integer&gt;(
07. 10);
08. public ThreadB(Exchanger&lt;Integer&gt; exchanger) {
09. this.exchanger = exchanger;
10. }
11. public void run() {
12. try {
13. while (true) {
14. last.set(exchanger.exchange(last.get()));
15. System.out.println(" After calling exchange. Thread B has value: " + last.get());
16. Thread.sleep(2000);
17. }
18. } catch (InterruptedException e) {
19. e.printStackTrace();
20. }
21. }
22. }

Java代码  [![收藏代码](http://mouselearnjava.iteye.com/images/icon_star.png)]()

1. package my.concurrent.exchanger;
2. import java.util.concurrent.Exchanger;
3. public class ExchangerTest {
4. public static void main(String\[] args) {
5. Exchanger&lt;Integer&gt; exchanger = new Exchanger&lt;Integer&gt;();
6. new Thread(new ThreadA(exchanger)).start();
7. new Thread(new ThreadB(exchanger)).start();
8. }
9. }

**运行一段时间之后的输出结果如下：**   
After calling exchange. Thread B has value: 5   
After calling exchange. Thread A has value: 10   
After calling exchange. Thread B has value: 10   
After calling exchange. Thread A has value: 5   
After calling exchange. Thread A has value: 10   
After calling exchange. Thread B has value: 5   
After calling exchange. Thread B has value: 10   
After calling exchange. Thread A has value: 5   
After calling exchange. Thread A has value: 10   
After calling exchange. Thread B has value: 5   
After calling exchange. Thread B has value: 10   
After calling exchange. Thread A has value: 5   
After calling exchange. Thread A has value: 10   
After calling exchange. Thread B has value: 5   
After calling exchange. Thread A has value: 5   
After calling exchange. Thread B has value: 10   
After calling exchange. Thread A has value: 10   
After calling exchange. Thread B has value: 5   
After calling exchange. Thread B has value: 10   
After calling exchange. Thread A has value: 5   
After calling exchange. Thread B has value: 5   
After calling exchange. Thread A has value: 10   
After calling exchange. Thread A has value: 5   
After calling exchange. Thread B has value: 10   
After calling exchange. Thread B has value: 5   
After calling exchange. Thread A has value: 10   
After calling exchange. Thread B has value: 10   
After calling exchange. Thread A has value: 5   
After calling exchange. Thread B has value: 5   
After calling exchange. Thread A has value: 10 

可以看出：两个线程的数据一直都在相互交换。