To achieve the exchange of data between two people, each person in the completion of a certain transaction to exchange data with each other, the first person to take out the data will be waiting for the second person to hold the data to each other to exchange data.
Copy Code code as follows:
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 = "John";
SYSTEM.OUT.PRINTLN ("Thread" + thread.currentthread (). GetName () + "is putting data ' + data1 + ' ' in exchange for");
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 = "Dick";
SYSTEM.OUT.PRINTLN ("Thread" + thread.currentthread (). GetName () + "is putting data ' + data1 + ' ' in exchange for");
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) {
}
}
});
}
}
return Result:
Copy Code code as follows:
Thread pool-1-thread-1 is changing the data ' John ' out
Thread pool-1-thread-2 is changing the data ' dick ' out
The data returned by the thread pool-1-thread-1 is ' dick '
The data returned by the thread pool-1-thread-2 is ' John '