It is used to achieve data exchange between two people. Everyone wants to exchange data with the other party after completing a certain deal. The first person who takes out the data will always wait for the second person to take the data to arrive in order to exchange the data with each other Essence
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 exchangrtest {
Public Static Void Main (String [] args) {{
ExecutorService Service = Executors.newcacheDthreadPool ();
FINAL Exchange Exchange = New Exchange ();
Service.execute (new runnable () {)
public void run () {
try {
String data1 = "Zhang San";
System.out.println ("thread" + thread.currentthRead (). GetName () + "is now turning the data '" + data1 + "' out");
Thread.sleep ((Long) (math.random ()*10000));
String data2 = (string) exchanger.exchange (data1);
System.out.println ("thread" + thread.currentthRead (). GetName () + "replaced data is '" + data2 + "'");
} Catch (Exception E) {{
}
}
});
Service.execute (new runnable () {)
public void run () {
try {
String data1 = "Li Si";
System.out.println ("thread" + thread.currentthRead (). GetName () + "is now turning the data '" + data1 + "' out");
Thread.sleep ((Long) (math.random ()*10000));
String data2 = (string) exchanger.exchange (data1);
System.out.println ("thread" + thread.currentthRead (). GetName () + "replaced data is '" + data2 + "'");
} Catch (Exception E) {{
}
}
});
}
}
Back results:
Copy code code as follows:
The thread POOL-Thread-1 is replacing the data 'Zhang San' out of the thread POOL-1-Thread-2 is changing the data to the thread POOL-Thread-1 '
The data of the thread POOL-1-Thread-2 is replaced by 'Zhang San'