Java multithreading-Exchanger, multithreading-exchanger
The synchronization point of the thread in which the elements can be paired and exchanged. Each thread presents a method on the entry to the exchange method, matches with the partner thread, and receives the object of its partner when returning the result. Exchanger may be considered as a bidirectional form of SynchronousQueue. Exchanger may be useful in applications such as genetic algorithms and pipeline design.
Exchanger provides an exchange service that allows atomic exchange of two (multiple) objects. At the same time, only one pair is successful.
Now start two threads, send one message separately, and then exchange information through exchanger.
Code:
1 public class ExchangerTest {2 public static void main (String [] args) {3 ExecutorService threadPool = Executors. newCachedThreadPool (); 4 final Exchanger exchanger = new Exchanger (); 5 6 threadPool.exe cute (new Runnable () {7 8 @ Override 9 public void run () {10 String date1 = "love"; 11 System. out. println ("Thread" + Thread. currentThread (). getName () + "putting data" + date1 +! "); 12 try {13 Thread. sleep (new Random (). nextInt (1000); 14} catch (InterruptedException e) {15 // TODO Auto-generated catch block16 e. printStackTrace (); 17} 18 String date2 = null; 19 try {20 date2 = (String) exchanger. exchange (date1); 21} catch (InterruptedException e) {22 // TODO Auto-generated catch block23 e. printStackTrace (); 24} 25 System. out. println ("Thread" + Thread. currentThread (). getName () + "Get To Data "+ date2); 26} 27}); 28 threadPool.exe cute (new Runnable () {29 30 @ Override31 public void run () {32 String date1 =" hate "; 33 System. out. println ("Thread" + Thread. currentThread (). getName () + "putting data" + date1 +! "); 34 try {35 Thread. sleep (new Random (). nextInt (1000); 36} catch (InterruptedException e) {37 // TODO Auto-generated catch block38 e. printStackTrace (); 39} 40 String date2 = null; 41 try {42 date2 = (String) exchanger. exchange (date1); 43} catch (InterruptedException e) {44 // TODO Auto-generated catch block45 e. printStackTrace (); 46} 47 System. out. println ("Thread" + Thread. currentThread (). getName () + "Get Data" + date2); 48} 49}); 50 51 threadPool. shutdown (); 52} 53}
Exchanger implements the idea of Data sharding, which has some practical value when data is divided into segments in big data and executed in multiple threads.