JAVA.util.concurrent.Exchanger类代表了两个线程在一个集合点可以交互数据 。下面描述了一下机制:
文章插图
两个线程通过Exchanger 正在交换对象数据
交换对象数据是通过 exchange()方法,下面是例子:
Exchanger exchanger = new Exchanger();ExchangerRunnable exchangerRunnable1 = new ExchangerRunnable(exchanger, "A"); ExchangerRunnable exchangerRunnable2 = new ExchangerRunnable(exchanger, "B"); new Thread(exchangerRunnable1).start();new Thread(exchangerRunnable2).start();
【JAVA多线程-Exchanger】 ExchangerRunnable代码:
public class ExchangerRunnable implements Runnable{ Exchanger exchanger = null; Object object = null; public ExchangerRunnable(Exchanger exchanger, Object object) { this.exchanger = exchanger; this.object = object; } public void run() { try { Object previous = this.object; this.object = this.exchanger.exchange(this.object); System.out.println(Thread.currentThread().getName() + " exchanged " + previous + " for " + this.object ); } catch (InterruptedException e) { e.printStackTrace(); } }}
执行结果:
Thread-0 exchanged A for BThread-1 exchanged B for A
参考翻译:http://tutorials.jenkov.com/java-util-concurrent/exchanger.html
推荐阅读
- MyBatis插件-慢sql耗时监控插件
- 霍山和黄芽属于哪种茶,霍山黄芽价格多少
- 教你如何解决Win10驱动升级Bug
- 如何使用Istio 1.6管理多集群中的微服务?
- 通俗易懂的讲解Java8 ParallelStream并发安全原理
- 人的潜能有多少 人类的潜能开发了多少
- 钓鱼最好的气压是多少?
- 世界上最重的牛有多少吨 世界最重的牛有多重
- 三角龙身长多少米 最大的翼龙长多少米
- 最大松鼠的体重多少 世界上最小的松鼠