Import Java.util.concurrent.Exchanger;
Import Java.util.concurrent.ExecutorService;
Import java.util.concurrent.Executors; /** * Multithreading exchange of data use the exchanger method to pass the data that you want to pass, and accept the number of other threads passing when returning * @author Bowin */public class Exchangetest {public S
tatic void Main (string[] args) {Executorservice service =executors.newcachedthreadpool ();
Final exchanger<object> exchanger = new exchanger<> ();
Service.execute (New Runnable () {@Override public void run () {try{
String data1 = "Snack";
SYSTEM.OUT.PRINTLN ("Thread" +thread.currentthread (). GetName () + "The data" +data1+ "to be replaced");
Thread.Sleep ((Long) math.random () *10000); String data2 = (string) exchanger.exchange (data1);/wait for other threads to execute the Exchange method and get the results of other threads ' execution System.out.println (
Thread +thread.currentthread (). GetName () + "The returned data is" +DATA2);
}catch (Exception e) {e.printstacktrace ();
}
}
});
Service.execute (New Runnable () {@Override public void run () {
try{String data1 = "Money";
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 () + "Exchange back data is:" +DATA2);
}catch (Exception e) {e.printstacktrace ();
}
}
}); }
}