The functionality of the Exchanger class enables the transfer of data between 2 threads, which is more convenient than the producer/consumer model.
The structure of the exchanger class is simple, and the focus is on the Exchange () method.
The Exchange () method is blocking execution, and you can set the time-out to invoke a different API.
Exchange is meant to be exchanged in English, and for threads it is two threads exchanging information. If there are 3 threads, and 3 threads call Exchange at the same time, then there will be a thread that does not exchange information, and it will continue to block.
Here is an example:
There are two classes of Exchangerthread, Exchangertest:
PackageCom.cd.concurrent.exchanger;ImportJava.util.concurrent.Exchanger;ImportJava.util.concurrent.TimeUnit;Importjava.util.concurrent.TimeoutException; Public classExchangerthreadextendsThread {PrivateExchanger<string>Exchanger; PrivateString name; PublicExchangerthread (String name, exchanger<string>Exchanger) { Super(); This. Name =name; This. Exchanger =Exchanger; } @Override Public voidrun () {Try { //System.out.println ("thread [" + name + "] Get message:" + exchanger.exchange (name + "-msg")); //without setting the timeout time, the thread will always block waitingSYSTEM.OUT.PRINTLN ("thread [" + name + "] Get message:" + exchanger.exchange (name + "-msg", 5, Timeunit.seconds));//set the time-out for 5 secondsSYSTEM.OUT.PRINTLN ("thread [" + Name + "]over"); } Catch(interruptedexception e) {e.printstacktrace (); } Catch(TimeoutException e) {//TODO auto-generated Catch blockE.printstacktrace (); } }}
PackageCom.cd.concurrent.exchanger;ImportJava.util.concurrent.Exchanger; Public classExchangertest { Public Static voidMain (string[] args) {Exchanger<String> exchanger =NewExchanger<string>(); Exchangerthread T1=NewExchangerthread ("T1", exchanger); Exchangerthread T2=NewExchangerthread ("T2", exchanger); exchangerthread T3=NewExchangerthread ("T3", exchanger); T1.start (); T2.start (); T3.start (); }}
Operation Result:
The use of "Java Concurrency Core II" exchanger