If two threads need to exchange information about each other during the running process, for example, a data or space, the Exchanger class is required. Exchanger provides a very convenient way for the thread to exchange information, it can be used as a synchronization point for two threads to exchange objects. Only when every thread enters the exchange () method and gives an object can it accept the objects given when other threads return.
The construction method of Exchanger is as follows:
[Java]
Exchanger (); // create a new Exchanger.
Exchanger uses the following methods:
[Java]
Exchange (V x); // wait for another thread to reach this switching point (unless it is interrupted), send the given object to this thread, and receive the object of this thread.
Exchange (V x, long timeout, TimeUnit unit); // wait for another thread to reach this switching point (unless it is interrupted or exceeds the specified wait time ), then, the given object is transmitted to the thread and the object of the thread is received.
The following is an example:
[Java]
Public class ExchangerTest {
Public static void main (String [] args ){
ExecutorService service = Executors. newCachedThreadPool ();
Final Exchanger exchanger = new Exchanger ();
Service.exe cute (new Runnable (){
Public void run (){
Try {
String data1 = "zxx ";
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 = "lhm ";
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 ){
}
}
});
}
}
In the preceding example, two threads are created in the main () method. Both threads have data of the String type and their sleep times are different. Class defines an Exchanger object as a channel for two threads to exchange data. When one thread runs exchanger. exchange (); method, because no other thread has not started to execute this exchange method, you need to wait until another thread also proposes the exchange, two threads can complete information exchange. The running result is as follows:
[Java]
Thread pool-1-thread-1 is changing the data zxx
The thread pool-1-thread-2 is replacing the data lhm.
The data returned by thread pool-1-thread-2 is zxx.
The data returned by thread pool-1-thread-1 is lhm.