First, brief
Exchanger can exchange data between two threads, only 2 threads, and he does not support the interchange of data between more than one thread. When thread A calls the Exchange () method of an Exchange object, he falls into a blocking state until thread B also calls the Exchange () method, and then swaps the data in a thread-safe fashion after threads A and b continue to run.
Second, code example
1 Public classExchangertest {2 3 Public Static voidMain (string[] args) {4Exchanger<string> Exchanger =NewExchanger<>();5Executorservice Executorservice = Executors.newfixedthreadpool (2);6String data = "";7Executorservice.execute (NewProcuder (data, exchanger));8Executorservice.execute (NewConsumer (data, exchanger));9 }Ten One } A - classProcuderImplementsrunnable{ - the PrivateString data; - PrivateExchanger<string>Exchanger; - PublicProcuder (String data,exchanger<string>Exchanger) { - This. data =data; + This. Exchanger =Exchanger; - } + A @Override at Public voidrun () { - - Try { - for(inti = 0; I < 5; i++) { -data =NewRandom (). Nextint (1000) + ""; -System.out.println ("producer" +i+ "" +data); inThread.Sleep (NewRandom (). Nextint (5) *1000); - exchanger.exchange (data); to } +}Catch(interruptedexception e) { - e.printstacktrace (); the } * } $ Panax Notoginseng } - the classConsumerImplementsrunnable{ + A PrivateString data; the PrivateExchanger<string>Exchanger; + PublicConsumer (String data,exchanger<string>Exchanger) { - This. data =data; $ This. Exchanger =Exchanger; $ } - - @Override the Public voidrun () { - Wuyi Try { the for(inti = 0; I < 5; i++) { -data =exchanger.exchange (data); WuThread.Sleep (NewRandom (). Nextint (5) *1000); -System.out.println ("Consumer" +i+ "" +data); About } $}Catch(interruptedexception e) { - e.printstacktrace (); - } - } A +}
Producer0 782503782367503 151 367 151
Exchanger sibling data information exchange between threads