- Exchanger的介绍
类Exchanger的功能可以使两个线程之间传输数据。
- 方法exchange()的使用
package com.wjg.unit; import java.util.concurrent.Exchanger; public class Run { public static void main(String[] args) { Exchanger<String> exchanger = new Exchanger<String>(); Run run =new Run(); ThreadA a = run.new ThreadA(exchanger); ThreadB b = run.new ThreadB(exchanger); a.start(); b.start(); } public class ThreadA extends Thread{ private Exchanger<String> exchanger; public ThreadA(Exchanger<String> exchanger) { super(); this.exchanger = exchanger; } @Override public void run() { try { String receive = exchanger.exchange("123"); System.out.println("在线程A中获得线程B的值:"+receive); } catch (InterruptedException e) { e.printStackTrace(); } } } public class ThreadB extends Thread{ private Exchanger<String> exchanger; public ThreadB(Exchanger<String> exchanger) { super(); this.exchanger = exchanger; } @Override public void run() { try { String receive = exchanger.exchange("456"); System.out.println("在线程B中获得线程A的值:"+receive); } catch (InterruptedException e) { e.printStackTrace(); } } } }
运行结果:
在线程A中获得线程B的值:456
在线程B中获得线程A的值:123
方法exchange(V x,long timeout,TimeUnit unit)的使用
此方法是指在指定的时间内没有其他线程获取数据,则出现超时异常。
package com.wjg.unit1; import java.util.concurrent.Exchanger; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; public class Run2 { public static void main(String[] args) { Exchanger<String> exchanger = new Exchanger<String>(); Run2 run =new Run2(); ThreadA a = run.new ThreadA(exchanger); a.start(); } public class ThreadA extends Thread{ private Exchanger<String> exchanger; public ThreadA(Exchanger<String> exchanger) { super(); this.exchanger = exchanger; } @Override public void run() { try {
//设置超时时间 String receive = exchanger.exchange("123",5,TimeUnit.SECONDS); System.out.println("在线程A中获得线程B的值:"+receive); } catch (InterruptedException e) { e.printStackTrace(); } catch (TimeoutException e) { e.printStackTrace(); } } } }
执行结果:
java.util.concurrent.TimeoutException
at java.util.concurrent.Exchanger.exchange(Exchanger.java:683)
at com.wjg.unit1.Run2$ThreadA.run(Run2.java:27)