Exchanger the synchronization point of a thread that can pair and swap elements in pairs. 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 as SynchronousQueue a bidirectional form. Exchanger may be useful in applications such as genetic algorithms and pipeline design.
Simulation is used to achieve the exchange of data between the two, each person to complete a certain transaction after the exchange of data, the first person to take out the data will be waiting for the second person to come out of the data to each other to exchange data.
public class Exchangertest {public static void main (string[] args) {Executorservice service = Executors.newcachedthreadpo OL (); final Exchanger Exchanger = new Exchanger (); Service.execute (new Runnable () {public void run () {try {String data1 = "JL J "; SYSTEM.OUT.PRINTLN ("Thread" + thread.currentthread (). GetName () + "data" + Data1 + "swap out"); Thread.Sleep ((Long) (Math.random () *10000)); String data2 = (string) exchanger.exchange (data1); SYSTEM.OUT.PRINTLN ("Thread" + thread.currentthread (). GetName () + "data returned as" + Data2);} catch (Exception e) {}}}); Service.execute (new Runnable () {public void run () {try {String data1 = "Ljy"; SYSTEM.OUT.PRINTLN ("Thread" + thread.currentthread (). GetName () + "data" + Data1 + "swap out"); Thread.Sleep ((Long) (Math.random () *10000)); String data2 = (string) exchanger.exchange (data1); SYSTEM.OUT.PRINTLN ("Thread" + thread.currentthread (). GetName () + "data returned as" + Data2);} catch (Exception e) {}}});}}
Results:
Thread pool-1-thread-1 is swapping out the data jlj.
Thread pool-1-thread-2 is swapping out the data ljy.
The data returned by thread pool-1-thread-2 is JLJ
The data returned by thread pool-1-thread-1 is Ljy
Exchanger of the Java Synchronization tool class