A synchronization point is defined between two threads, and when two threads reach the synchronization point, they exchange data structures, so the data structure of the first thread goes into the second thread, and the data structure of the second thread goes into the first thread
In the producer-consumer context model it contains a number of buffers, one or more producers, one or more consumers
Here are examples of producers and consumers:
/*** Exchange of data between producers and consumers*/ Public classMyexchanger { Public Static voidMain (string[] args) {Exchanger<List<String>> exchanger =NewExchanger<list<string>>(); Producer1 producer=NewProducer1 (NewArraylist<string>(), exchanger); Consumer1 Consumer=NewConsumer1 (NewArraylist<string>(), exchanger); NewThread (producer). Start (); NewThread (consumer). Start (); }}/**Producer Threads*/ classProducer1Implementsrunnable{/*** Storage of exchanged data*/ PrivateList<string>buffer; /*** and consumers to exchange the object*/ Private FinalExchanger<list<string>>Exchanger; Producer1 (List<String> buffer,exchanger<list<string>>Exchanger) { This. Buffer =buffer; This. Exchanger =Exchanger; } @Override Public voidrun () { for(inti = 0; I < 2; i++) {String message= "" +i; System.out.println ("Produce data:" +message); Buffer.add (message); //Call Exchange () to exchange data with consumers Try{buffer=exchanger.exchange (buffer); } Catch(interruptedexception e) {e.printstacktrace (); }} System.out.println ("Produce received the length of the data from consumer:" +buffer.size ()); }} /**Consumer Threads*/ classConsumer1Implementsrunnable{PrivateList<string>buffer; Private FinalExchanger<list<string>>Exchanger; PublicConsumer1 (list<string> buffer,exchanger<list<string>>Exchanger) { This. Buffer =buffer; This. Exchanger =Exchanger; } @Override Public voidrun () { for(inti = 0; I < 2; i++){ //Call Exchange () to exchange data with consumers Try{buffer=exchanger.exchange (buffer); } Catch(interruptedexception e) {e.printstacktrace (); } for(intj = 0; J < Buffer.size (); J + +) {System.out.println ("Consumer received data from produce:" + buffer.get (0)); Buffer.remove (0); }} System.out.println ("Consumer Erase Data"); } }
Console output:
produce data: 0 0101Consumer clear the data
In exchanger, if a thread has reached the exchanger node, there are three scenarios for its partner node:
1, if its partner node has called the exchanger method between the time the thread arrives, it wakes its partner and then exchanges the data to get the respective data back.
2, if its partner node has not reached the exchange point, then the thread will be suspended, waiting for its partner node to wake up to complete the data exchange.
3, throws an exception if the current thread is interrupted, or waits for a timeout, throwing a time-out exception
Java concurrent Programming--6.exchanger data interchange between threads