Exchanger用于两个工作线程之间交换数据
线程A与线程B交换数据,当线程到达交换点直接交换,另一个等待的A线程立即被唤醒,而不是等B线程执行完再唤醒
public class test03 {public static void main(String[] args) {Exchanger<Integer> exchanger=new Exchanger<>();Thread t1=new Thread(new A(exchanger,1,0));Thread t2=new Thread(new A(exchanger,10,2000));t1.start();t2.start();}
}class A implements Runnable {private Exchanger<Integer> exchanger;private Integer data;private long wait;public A(Exchanger<Integer> exchanger, Integer data, long wait) {this.exchanger = exchanger;this.data = data;this.wait = wait;}@Overridepublic void run() {try {System.out.println(Thread.currentThread().getName()+":"+data);Thread.sleep(wait);data = exchanger.exchange(data);System.out.println(Thread.currentThread().getName()+":"+data);Thread.sleep(wait);} catch (InterruptedException e) {e.printStackTrace();}}
}
例子中,线程t1等待t2到达交换点,当t2达到交换点后,交换数据,t1立即唤醒(此时t2线程进入sleep没有执行完,但t1不受影响,唤醒后继续执行)