Reproduced in: http://janeky.iteye.com/blog/769965
Let's start by learning more about this class in the JDK1.5 API:
"The synchronization point of a thread that can pair and swap elements in a pair." Each thread renders a method on the entry to the Exchange method, matches the partner thread, and receives the object of its partner when it returns. Exchanger may be considered a bidirectional form of synchronousqueue. Exchanger may be useful in applications such as genetic algorithms and pipeline design. “
Application Example: There are two buffers, two threads to two buffers fill and take, when and only if a full, two buffer swap
The code is as follows
Package Com.winterbe.java8.samples.concurrent;import Java.util.arraylist;import Java.util.concurrent.Exchanger; public class Testexchanger {public static void main (string[] args) {final exchanger<arraylist<integer>> Exchanger = new exchanger<arraylist<integer>> (); final arraylist<integer> buff1 = new arraylist< Integer> (ten); final arraylist<integer> buff2 = new arraylist<integer> (ten); final Arraylist<integer > buff3 = new arraylist<integer>, new Thread (new Runnable () {@Overridepublic void run () {arraylist< integer> buff = buff1;try {while (true) {if (Buff.size () >=) {buff = Exchanger.exchange (buff);//start interacting with another thread of data Syst Em.out.println ("Exchange buff1"); Buff.clear ();} Buff.add ((int) (Math.random () *100)); Thread.Sleep ((Long) (Math.random () *1000));}} catch (Interruptedexception e) {e.printstacktrace ();}}}). Start (); New Thread (New Runnable () {@Overridepublic void run () {arraylist<integer> Buff=buff2;while (true) {try { for (IntegEr i:buff) {System.out.println ("B2:" +i);} Thread.Sleep (+); Buff=exchanger.exchange (buff);//Start exchanging data System.out.println ("Exchange Buff2") with another thread;} catch (Interruptedexception e) {e.printstacktrace ();}}}}). Start (); New Thread (New Runnable () {@Overridepublic void run () {arraylist<integer> Buff=buff3;while (true) {try { for (Integer I:buff) {System.out.println ("B3:" +i);} Thread.Sleep (+); Buff=exchanger.exchange (buff);//Start exchanging data System.out.println ("Exchange BUFF3") with another thread;} catch (Interruptedexception e) {e.printstacktrace ();}}}}). Start ();}}
Summary: Exchanger is useful for specific usage scenarios (data interaction between two partner threads)
Java Multithreaded Learning-java.util.concurrent detailed (vi) Exchanger