Exchanger is a tool class for inter-thread co-use, primarily for data exchange between threads. It provides a synchronization point at which two threads can exchange data with each other. Two threads Exchange data through Exchange methods, and if one thread executes an Exchange method, it waits for another thread to execute the Exchange method, and when two threads reach the synchronization point, the two threads can exchange data. Transfer the data generated by this thread to the other party.
Exchanger can be used for the work of mutual proofreading, for example, we want to put the transaction data generated by manual input into the system, in order to avoid errors, we use AB two simultaneous input method, when the input is completed, the system load AB two input data, check whether the error.
The simulation examples are as follows:
Public classExchangertest {//Defining the Exchanger Private Static FinalExchanger<string> Exchanger =NewExchanger<string>(); Private StaticExecutorservice ThreadPool = Executors.newfixedthreadpool (2); Public Static voidMain (string[] args) {Threadpool.execute (NewRunnable () {@Override Public voidrun () {String stra= "A record Data"; Try{exchanger.exchange (stra); } Catch(interruptedexception e) {e.printstacktrace (); } } }); Threadpool.execute (NewRunnable () {@Override Public voidrun () {Try{String StrB= "B Record Data"; String Stra=Exchanger.exchange (StrB); System.out.println (Stra.equals (StrB)); Exchanger.exchange (StrB); } Catch(interruptedexception e) {e.printstacktrace (); } } }); }}
If two threads have one without the Exchange () method, you can wait until you are concerned about special circumstances and avoid waiting for the maximum wait time to be set using Exchange (V x,longtimeout,timeunit unit).
Java Concurrency Tool class inter-threading data exchange tool exchanger