ITeye博客

Java并发编程: 使用Exchanger实现线程间的数据交换

iaspecwang · 2013-08-25 17:32 · java线程 · 企业架构 · Markdown

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

1. Exchanger介绍 

Java代码  收藏代码

  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类内容如下: 

 

Java代码  收藏代码

  1. package java.util.concurrent;
  2. import java.util.concurrent.locks.*;
  3. /**
  4. * A synchronization point at which two threads can exchange objects.
  5. * Each thread presents some object on entry to the {@link #exchange
  6. * exchange} method, and receives the object presented by the other
  7. * thread on return.
  8. *
  9. * <p><b>Sample Usage:</b>
  10. * Here are the highlights of a class that uses an <tt>Exchanger</tt> to
  11. * swap buffers between threads so that the thread filling the
  12. * buffer gets a freshly
  13. * emptied one when it needs it, handing off the filled one to
  14. * the thread emptying the buffer.
  15. * <pre>
  16. * class FillAndEmpty {
  17. *   Exchanger<DataBuffer> exchanger = new Exchanger();
  18. *   DataBuffer initialEmptyBuffer = ... a made-up type
  19. *   DataBuffer initialFullBuffer = ...
  20. *
  21. *   class FillingLoop implements Runnable {
  22. *     public void run() {
  23. *       DataBuffer currentBuffer = initialEmptyBuffer;
  24. *       try {
  25. *         while (currentBuffer != null) {
  26. *           addToBuffer(currentBuffer);
  27. *           if (currentBuffer.full())
  28. *             currentBuffer = exchanger.exchange(currentBuffer);
  29. *         }
  30. *       } catch (InterruptedException ex) { ... handle ... }
  31. *     }
  32. *   }
  33. *
  34. *   class EmptyingLoop implements Runnable {
  35. *     public void run() {
  36. *       DataBuffer currentBuffer = initialFullBuffer;
  37. *       try {
  38. *         while (currentBuffer != null) {
  39. *           takeFromBuffer(currentBuffer);
  40. *           if (currentBuffer.empty())
  41. *             currentBuffer = exchanger.exchange(currentBuffer);
  42. *         }
  43. *       } catch (InterruptedException ex) { ... handle ...}
  44. *     }
  45. *   }
  46. *
  47. *   void start() {
  48. *     new Thread(new FillingLoop()).start();
  49. *     new Thread(new EmptyingLoop()).start();
  50. *   }
  51. * }
  52. * </pre>
  53. *
  54. * @since 1.5
  55. * @author Doug Lea
  56. * @param <V> The type of objects that may be exchanged
  57. */
  58. public class Exchanger<V> {
  59. private final ReentrantLock lock = new ReentrantLock();
  60. private final Condition taken = lock.newCondition();
  61. /** Holder for the item being exchanged */
  62. private V item;
  63. /**
  64. * Arrival count transitions from 0 to 1 to 2 then back to 0
  65. * during an exchange.
  66. */
  67. private int arrivalCount;
  68. /**
  69. * Main exchange function, handling the different policy variants.
  70. */
  71. private V doExchange(V x, boolean timed, long nanos) throws InterruptedException, TimeoutException {
  72. lock.lock();
  73. try {
  74. V other;
  75. // If arrival count already at two, we must wait for
  76. // a previous pair to finish and reset the count;
  77. while (arrivalCount == 2) {
  78. if (!timed)
  79. taken.await();
  80. else if (nanos > 0)
  81. nanos = taken.awaitNanos(nanos);
  82. else
  83. throw new TimeoutException();
  84. }
  85. int count = ++arrivalCount;
  86. // If item is already waiting, replace it and signal other thread
  87. if (count == 2) {
  88. other = item;
  89. item = x;
  90. taken.signal();
  91. return other;
  92. }
  93. // Otherwise, set item and wait for another thread to
  94. // replace it and signal us.
  95. item = x;
  96. InterruptedException interrupted = null;
  97. try {
  98. while (arrivalCount != 2) {
  99. if (!timed)
  100. taken.await();
  101. else if (nanos > 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. * <p>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. * <p>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. * <li>Some other thread enters the exchange; or
  151. * <li>Some other thread {@link Thread#interrupt interrupts} the current
  152. * thread.
  153. * [/list]
  154. * <p>If the current thread:
  155. * [list]
  156. * <li>has its interrupted status set on entry to this method; or
  157. * <li>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. * <p>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. * <p>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. * <li>Some other thread enters the exchange; or
  192. * <li>Some other thread {@link Thread#interrupt interrupts} the current
  193. * thread; or
  194. * <li>The specified waiting time elapses.
  195. * [/list]
  196. * <p>If the current thread:
  197. * [list]
  198. * <li>has its interrupted status set on entry to this method; or
  199. * <li>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. * <p>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 <tt>timeout</tt> 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代码  收藏代码

  1. package my.concurrent.exchanger;
  2. import java.util.concurrent.Exchanger;
  3. import java.util.concurrent.atomic.AtomicReference;
  4. public class ThreadA implements Runnable {
  5. private final Exchanger<Integer> exchanger;
  6. private final AtomicReference<Integer> last = new AtomicReference<Integer>(
  7. 5);
  8. public ThreadA(Exchanger<Integer> exchanger) {
  9. 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代码  收藏代码

  1. package my.concurrent.exchanger;
  2. import java.util.concurrent.Exchanger;
  3. import java.util.concurrent.atomic.AtomicReference;
  4. public class ThreadB implements Runnable {
  5. private Exchanger<Integer> exchanger;
  6. private final AtomicReference<Integer> last = new AtomicReference<Integer>(
  7. 10);
  8. public ThreadB(Exchanger<Integer> exchanger) {
  9. 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代码  收藏代码

  1. package my.concurrent.exchanger;
  2. import java.util.concurrent.Exchanger;
  3. public class ExchangerTest {
  4. public static void main(String[] args) {
  5. Exchanger<Integer> exchanger = new Exchanger<Integer>();
  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 

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

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。