It is used to exchange data between two people. Each person wants to exchange data with the other party after completing a certain transaction, the first person who obtains the data will wait until the second person receives the data before they can exchange data.
That is, when both threads reach the switching point, they can be switched. Public static void main (string [] ARGs ){
Executorservice service = executors. newcachedthreadpool (); Final exchanger = new exchanger (); service.exe cute (New runnable () {public void run () {try {string data1 = "money"; system. out. println ("Thread" + thread. currentthread (). getname () + "changing data" + data1 + "); thread. sleep (long) (math. random () * 10000 ));
string data2 = (string) exchanger. Exchange (data1); System. out. println ("Thread" + thread. currentthread (). getname () + "the returned data is" + data2);} catch (exception e) {}}); service.exe cute (New runnable () {public void run () {try {string data1 = "drugs"; system. out. println ("Thread" + thread. currentthread (). getname () + "changing data" + data1 + "); thread. sleep (long) (math. random () * 10000 ));
String data2 = (string) exchanger. Exchange (data1 ); System. out. println ("Thread" + thread. currentthread (). getname () + "the returned data is" + data2);} catch (exception e ){}}});
}
The running result is as follows:
Reprinted please indicate the source: http://blog.csdn.net/johnny901114/article/details/8696019