Exchanger<v>
V-Types of objects that can be exchanged
The synchronization point of the thread that can pair and swap elements in pairs. Each thread renders a method on the entry to the Exchange method, matches the partner thread, and receives the object of its partner when it returns. Exchanger may be considered a bidirectional form of synchronousqueue. Exchanger may be useful in applications such as genetic algorithms and pipeline design.
This implementation is an exchange of information between two threads
Public class testexchanger { Public Static void Main(string[] args) {System.out.println ("Hello world!");FinalExchanger<list<integer>> Exchanger =NewExchanger<list<integer>> ();NewThread () {@Override Public void Run() {list<integer> L =NewArraylist<integer> (); L.add (1); L.add (2);Try{System.out.println (Thread.CurrentThread (). GetName () +":"+L); L = Exchanger.exchange (l); }Catch(Interruptedexception ex) {Ex.printstacktrace (); } System.out.println (Thread.CurrentThread (). GetName () +":"+L); }}.start ();NewThread () {@Override Public void Run() {list<integer> L =NewArraylist<integer> (); L.add (3); L.add (4);Try{System.out.println (Thread.CurrentThread (). GetName () +":"+L); Thread.Sleep ( -); L = Exchanger.exchange (l); }Catch(Interruptedexception ex) {Ex.printstacktrace (); } System.out.println (Thread.CurrentThread (). GetName () +":"+L); }}.start (); }}
Adding a thread.sleep () will reveal that two threads exchange information ends in order to execute down simultaneously
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
The exchanger of Java concurrent programming