Exchanger
Exchanger, in the name of the understanding is the exchange. The exchanger is used to exchange data between two threads, noting that data exchange can only be done between two threads. The thread blocks on the exchanger exchange method until another thread has reached the same exchanger exchange method, exchanging data, and then two threads continue to execute their own related code.
Exchanger has only one exchange method for exchanging data. Take a look at the example:
Public Static classExchangerthreadextendsthread{PrivateString str; PrivateExchanger<string>Exchanger; Private intSleepsecond; PublicExchangerthread (String str, exchanger<string> Exchanger,intSleepsecond) { This. str =str; This. Exchanger =Exchanger; This. Sleepsecond =Sleepsecond; } Public voidrun () {Try{System.out.println ( This. GetName () + "Start, the original data is" + str + ", the time is" +System.currenttimemillis ()); Thread.Sleep (Sleepsecond* 1000); STR=Exchanger.exchange (str); System.out.println ( This. GetName () + "Exchange data, after Exchange data is" + str + ", Time is" +System.currenttimemillis ()); } Catch(interruptedexception e) {e.printstacktrace (); } }} Public Static voidMain (string[] args) {Exchanger<String> exchanger =NewExchanger<string>(); Exchangerthread et0=NewExchangerthread ("111", exchanger, 3); Exchangerthread Et1=NewExchangerthread ("222", Exchanger, 2); Et0.start (); Et1.start ();}
Look at the results of the operation:
thread-0 Start, the original data is 111, time is 1444560972303Thread-1 start, the original data is 222, time is 1444560972303Thread-0 Exchange data, The data after Exchange is 222, time is 1444560975303Thread-1 Exchange data, the data after Exchange is 111, time is 1444560975303
See two threads exchanged data, because a thread sleeps 2 seconds, a thread sleeps 3 seconds, since to exchange data, must sleep 2 seconds to wait for 3 seconds to sleep, so see the time difference is 3000ms is 3s.
PS: The feeling here is that a thread needs another thread to synchronize with him, and can also be used as a conduit for mutual notification, first mark
Java Multi-Threading 29: Exchanger of Multithreaded components