Preface
?? In order to handle synchronization between threads, the JDK provides several useful concurrency tool classes in addition to the lock mechanism: Countdownlatch, Cyclicbarrier, Semphore, Exchanger, Phaser;
?? Countdownlatch, Cyclicbarrier, Semphore, Phaser These four tool classes provide a control of the concurrency process, while the Exchanger tool class provides a means of exchanging data between threads.
Introduction
?? Exchanger's function is to enable the exchange of data between 2 threads (there are many articles that are "transmitting data", it should be called "exchange of data" more appropriate, because this is two threads to each other to transmit data, but also to get the other side of the data sent over, is bidirectional mode, Not one thread transmits data to another thread). It is more convenient than the wait/notify used by the producer/consumer model.
?? The Exchanger provides a synchronization point at which two threads can exchange data from each other. That is, one thread calls the Exchange () method to Exchange data, reaches the synchronization point, and then blocks until another thread calls the Exchange () method to exchange data. Therefore, be aware that the Exchange () method is a blocking feature.
Exchanger may be useful in applications such as genetic algorithms and pipeline design.
Method Summary
Public V Exchange (v x) throws Interruptedexception
Waits for another thread to reach this interchange point (unless the current thread is interrupted), then routes the given object to that thread and receives the object for that thread.
Public v Exchange (v X, long timeout, timeunit unit) throws Interruptedexception, TimeoutException
Waits for another thread to reach this interchange point (unless the current thread is interrupted, or the specified wait time is exceeded), and then the given object is passed to the thread, and the thread is received
@ Example1? Usage examples
The following is a highlighted class that uses Exchanger to swap buffers between threads, so that when needed, the thread that fills the buffer gets a new vacated buffer and passes the filled buffer to the thread that empties the buffer
classFillandempty {exchanger<databuffer> Exchanger =NewExchanger<databuffer> (); DataBuffer Initialemptybuffer =... A made-up type databuffer Initialfullbuffer = ...classFillingloopImplementsRunnable { Public void Run() {DataBuffer currentbuffer = Initialemptybuffer;Try{ while(Currentbuffer! =NULL) {Addtobuffer(Currentbuffer);if(Currentbuffer.Isfull()) Currentbuffer = exchanger.Exchange(Currentbuffer); } }Catch(Interruptedexception ex) {... Handle... } } }classEmptyingloopImplementsRunnable { Public void Run() {DataBuffer currentbuffer = Initialfullbuffer;Try{ while(Currentbuffer! =NULL) {Takefrombuffer(Currentbuffer);if(Currentbuffer.IsEmpty()) Currentbuffer = exchanger.Exchange(Currentbuffer); } }Catch(Interruptedexception ex) {... Handle ...} } }void Start() {NewThread (New Fillingloop()).Start();NewThread (New Emptyingloop()).Start(); } }
@ Example2? scenario Example
Exchanger can be used in genetic algorithms where two people are chosen as mating objects, and the data for two people is exchanged, and 2 mating results are obtained using cross-rules.
Exchanger can also be used for proofreading work. For example, we need to paper silver flow through manual input into the electronic bank water, in order to avoid errors, the use of AB Gang two people to enter, entered into Excel, the system needs to load the two Excel, and the two Excel data to proofread, to see if the input is consistent. The code is as follows:
Private Static FinalExchanger<string> exgr =NewExchanger<string> ();Private StaticExecutorservice ThreadPool = executors.Newfixedthreadpool(2); Public Static void Main(string[] args) {ThreadPool.Execute(NewRunnable () {@Override Public void Run() {Try{String A ="Bank of Water a";//A input bank dataExgr.Exchange(A);//Sync points, exchanging data}Catch(Interruptedexception e) { } } }); ThreadPool.Execute(NewRunnable () {@Override Public void Run() {Try{String B ="Bank of Water B";//b input Bank flow dataString A = exgr.Exchange("B");//Sync points, exchanging dataSystem. out.println("A and B data are consistent:"+ A.equals(B) +"\ nA entry is: "+ A +"\ nb The entry is: ", e); }Catch(Interruptedexception e) { } } }); ThreadPool.shutdown();}
Operation Result:
Whether A and B data are consistent: false
A input is: Bank of water A
b input is: Bank of Water B
Literature:
- The art of Java concurrent programming
Concurrency tool Class (iv) exchanging data between threads Exchanger