Java concurrent programming: Exchanger
Exchanger
V-object types that can be exchanged
The synchronization point of the thread in which the elements can be paired and exchanged. Each thread presents a method on the entry to the exchange method, matches with the partner thread, and receives the object of its partner when returning the result. Exchanger may be considered as a bidirectional form of SynchronousQueue. Exchanger may be useful in applications such as genetic algorithms and pipeline design.
This is an information exchange between two threads.
public class TestExchanger { public static void main(String[] args) { System.out.println(Hello World!); final Exchanger
> exchanger = new Exchanger
>(); new Thread(){ @Override public void run(){ List
l = new ArrayList
(); 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(); new Thread(){ @Override public void run(){ List
l = new ArrayList
(); l.add(3); l.add(4); try{ System.out.println(Thread.currentThread().getName()+:+l); Thread.sleep(2000); l = exchanger.exchange(l); }catch(InterruptedException ex){ ex.printStackTrace(); } System.out.println(Thread.currentThread().getName()+:+l); } }.start(); }}
After you add a Thread. sleep (), you will find that the information exchange between the two threads ends before the two threads can be executed downstream simultaneously.