For data exchange between two people, everyone wants to exchange data with each other after completing a certain transaction, the first person to come up with the data will wait until the second person is holding the data to exchange data with each other.
Package Com.ljq.test.thread;import Java.util.concurrent.exchanger;import Java.util.concurrent.ExecutorService; Import Java.util.concurrent.executors;public class Exchangertest {public static void main (string[] args) { Executorservice service = Executors.newcachedthreadpool (); final Exchanger Exchanger = new Exchanger (); Service.execute ( New Runnable () {public void run () {try {String data1 = "Zhang San"; 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 () + "return the data as '" + data2+ "'");} catch (Exception e) {}}}); Service.execute (new Runnable () {public void run () {try {String data1 = "John Doe"; 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 () + "swapped back data""+ data2 +" ' ");} catch (Exception e) {}}});}}
return Result:
Thread pool-1-thread-1 is taking the data ' Zhang San ' out of the thread pool-1-thread-2 is putting the data ' John Doe ' out of the thread pool-1-thread-1 swapped back the data for ' John Doe ' thread pool-1-thread-2 the data returned as ' Zhang San
JAVA5 Exchanger Data Interchange