同步辅助工具类中的Exchanger的作用是在成对的线程之间相互传递消息,通过exchange()方法进行交换数据。例如如下示例:
public class TestExchanger { public static void main(String[] args) throws InterruptedException { Exchanger<People> exchanger=new Exchanger<>(); Thread t1=new Thread(new TestExchangerThread(new People("小明",10),exchanger,0),"小明线程 "); Thread t2=new Thread(new TestExchangerThread(new People("小红",20),exchanger,10),"小红线程 "); t1.start(); t2.start(); t1.join(); t2.join(); System.out.println("主线程完毕"); } } class TestExchangerThread implements Runnable{ private Exchanger<People> exchanger; private int seconds; private People people; public TestExchangerThread(People people,Exchanger<People> exchanger,int seconds) { this.people = people; this.exchanger=exchanger; this.seconds=seconds; } @Override public void run() { System.out.println(Thread.currentThread().getName()+"得到交换之前的值为"+people); try { if(seconds>0){ TimeUnit.SECONDS.sleep(seconds); } People exchange = exchanger.exchange(people); System.out.println(Thread.currentThread().getName()+"得到交换之后的值为"+exchange); } catch (InterruptedException e) { e.printStackTrace(); } } }
这个例子中的exchanger.exchange()方法是一个同步点,如果其他的线程没有到达这个同步点就会阻塞当前线程。