首页 > 代码库 > Java并发程序设计(21)并发锁之交换器Exchanger
Java并发程序设计(21)并发锁之交换器Exchanger
1.1. 交换器Exchanger
Exchanger用于在两个线程之间同步的同时交换数据,并且仅仅可以用于两个线程之间,不支持多个线程之间交换。
package com.test.concurrence; import java.util.concurrent.Exchanger; public class ExchangerTest { public static void main(String[] args) { //待交换数据的类型为字符串。 final Exchanger<String> exchanger = new Exchanger<String>(); String[] tags = new String[]{"A","B"}; for(int j=0;j<2;j++){ final String tag = tags[j]; new Thread( new Runnable(){ @Override public void run(){ for(int i=0;i<10;i++){ try { String old = tag+i; //执行效果:对方变成old,自己得到result。 Object result = exchanger.exchange(old); System.out.println( old + " => " + result +" , " + Thread.currentThread().getName()); } catch (InterruptedException e) { e.printStackTrace(); } } } }).start(); } } }
运行结果如下:
A0 => B0 , Thread-0
B0 => A0 , Thread-1
B1 => A1 , Thread-1
A1 => B1 , Thread-0
A2 => B2 , Thread-0
B2 => A2 , Thread-1
A3 => B3 , Thread-0
B3 => A3 , Thread-1
B4 => A4 , Thread-1
A4 => B4 , Thread-0
A5 => B5 , Thread-0
B5 => A5 , Thread-1
B6 => A6 , Thread-1
A6 => B6 , Thread-0
A7 => B7 , Thread-0
B7 => A7 , Thread-1
A8 => B8 , Thread-0
B8 => A8 , Thread-1
B9 => A9 , Thread-1
A9 => B9 , Thread-0
Java并发程序设计(21)并发锁之交换器Exchanger
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。