Exchanger usage in java threads
Sometimes we need to pair the elements and synchronize the exchange threads, and use the exchange method to return the objects of our partners. In this case, we need to use the Exchanger class in the Thread class,
I use an instance to briefly describe how to use it and its role:
Import java. util. concurrent. exchanger; import java. util. concurrent. executorService; import java. util. concurrent. executors; public class TestExchanger {/*** @ param args */public static void main (String [] args) {ExecutorService executor = Executors. newCachedThreadPool (); final Exchanger
Exchanger = new Exchanger
(); Executor.exe cute (new Runnable () {String data1 = "abc"; @ Overridepublic void run () {try {System. out. println (Thread. currentThread (). getName () + "Switching Data" + data1 + "); Thread. sleep (long) (Math. random () * 1000); String data2 = (String) exchanger. exchange (data1); System. out. println (Thread. currentThread (). getName () + "exchange data to" + data2);} catch (InterruptedException e) {e. printStackTrace () ;}}); executor.exe cute (new Runnable () {String data1 = "def"; @ Overridepublic void run () {try {System. out. println (Thread. currentThread (). getName () + "Switching Data" + data1 + "); Thread. sleep (long) (Math. random () * 1000); String data2 = (String) exchanger. exchange (data1); System. out. println (Thread. currentThread (). getName () + "exchange data to" + data2);} catch (InterruptedException e) {e. printStackTrace ();}}});}}
After the execution is completed, you will find that the data has been exchanged
Pool-1-thread-1 is exchanging data abc
Pool-1-thread-2 is switching data def
Pool-1-thread-2 swap data to abc
Pool-1-thread-1 swap data to def