Exchanger

A synchronization point at which threads can pair and swap elements within pairs. Each thread presents some object on entry to the exchange method, matches with a partner thread, and receives its partner's object on return. An Exchanger may be viewed as a bidirectional form of a SynchronousQueue. Exchangers may be useful in applications such as genetic algorithms and pipeline designs.


package exchange;

import java.util.concurrent.Exchanger;

/**   
 * @author YYZ  
 * @version 2011-10-26 上午11:37:44
 */
/** 
 * 案例:服务员向原有空杯中不断倒水,消费者不断从原有装满水的杯中喝水。  
 * 当服务员倒满水和消费者喝完水时,两个杯子进行交换。一直这样周而复始。 
 *  
 * @author Administrator 
 *  
 */  
public class TestExchanger {  
  
    static Exchanger<Cup> exchanger = new Exchanger<Cup>();  
    static Cup emptyCup = new Cup(0);  
    static Cup fullCup = new Cup(100);  
  
    public static void main(String[] args) {  
        new Thread(new Waiter(3)).start();  
        new Thread(new Customer(6)).start(); 
    }  
  
    /** 
     * 服务员 
     *  
     * @author Administrator 
     *  
     */  
    static class Waiter implements Runnable {  
  
        int addSpeed = 1;  
  
        public Waiter(int addSpeed) {  
            this.addSpeed = addSpeed;  
        }  
  
        @Override  
        public void run() {  
            while (emptyCup != null) {  
                // 如果发现杯子中的水没有满,则往杯中加水。  
                try {  
                    if (emptyCup.isFull()) {// 当emptyCup为装满水时并且fullCup为被喝完水时,进行交换。  
                        // 当Waiter把杯子水装满后,与Customer交换杯子。  
                        // exchange(emptyCup)中参数的emptyCup是waiter装满水后的,把装满水后的emptyCup参数传递给Cutomer线程。  
                        // 并且返回Cutomer线程中fullCup给Waiter的emptyCup,这样就达到了交换效果。  
                        emptyCup = exchanger.exchange(emptyCup);  
                        System.out.println("Waiter: " + emptyCup.capacity);  
                    } else {  
                        emptyCup.addWaterToCup(3);  
                        System.out.println("Waiter add " + addSpeed  
                                + " and current capacity is "  
                                + emptyCup.capacity);  
                        Thread.sleep((long) (Math  
                                .max(500, Math.random() * 2000)));  
                    }  
                } catch (InterruptedException e) {  
                    e.printStackTrace();  
                }  
            }  
        }  
    }  
  
    /** 
     * 消费者 
     *  
     * @author Administrator 
     *  
     */  
    static class Customer implements Runnable {  
  
        int drinkSpeed = 1;  
  
        public Customer(int drinkSpeed) {  
            this.drinkSpeed = drinkSpeed;  
        }  
  
        @Override  
        public void run() {  
            while (fullCup != null) {  
                // 如果发现杯子中的水没有满,则往杯中加水。  
                try {  
                    if (fullCup.isEmpty()) {  
                        // 水满后则交换子中的水  
                        fullCup = exchanger.exchange(fullCup);  
                        System.out.println("Customer: " + fullCup.capacity);  
                    } else {  
                        fullCup.drinkFormCup(drinkSpeed);  
                        System.out.println("Customer drinked " + drinkSpeed  
                                + " and current capacity is "  
                                + fullCup.capacity);  
                        Thread.sleep((long) (Math  
                                .max(500, Math.random() * 2000)));  
                    }  
  
                } catch (InterruptedException e) {  
                    e.printStackTrace();  
                }  
            }  
        }  
  
    }  
  
    static class Cup {  
  
        private int capacity = 0;  
  
        public Cup(int capacity) {  
            this.capacity = capacity;  
        }  
  
        public void addWaterToCup(int i) {  
            capacity += i;  
            capacity = capacity > 100 ? 100 : capacity;  
        }  
  
        public void drinkFormCup(int i) {  
            capacity -= i;  
            capacity = capacity < 0 ? 0 : capacity;  
        }  
  
        public boolean isFull() {  
            return capacity == 100 ? true : false;  
        }  
  
        public boolean isEmpty() {  
            return capacity == 0 ? true : false;  
        }  
    }  
  
}  

Customer drinked 6 and current capacity is 24
Waiter add 3 and current capacity is 3
Customer drinked 6 and current capacity is 18
Waiter add 3 and current capacity is 6
Customer drinked 6 and current capacity is 12
Waiter add 3 and current capacity is 9
Customer drinked 6 and current capacity is 6
Waiter add 3 and current capacity is 12
Waiter add 3 and current capacity is 15
Customer drinked 6 and current capacity is 0
Waiter add 3 and current capacity is 18
Waiter add 3 and current capacity is 21
Waiter add 3 and current capacity is 24
Waiter add 3 and current capacity is 27
Waiter add 3 and current capacity is 30
Waiter: 0
Waiter add 3 and current capacity is 3
Customer: 30
Customer drinked 6 and current capacity is 24
Waiter add 3 and current capacity is 6

<think>嗯,用户让我介绍一下JUC里的Exchanger,我得先回忆一下相关知识。Exchanger是Java并发工具中的一个类,主要用于两个线程之间交换数据。可能用户已经对CountDownLatch、CyclicBarrier这些有所了解,现在想扩展到更少见的同步工具。 首先,我需要确定Exchanger的基本概念。它允许两个线程在某个同步点交换彼此的数据。比如,一个线程生产数据,另一个消费,他们可以用Exchanger来交换数据。这点需要明确说明,可能用户需要知道使用场景。 然后,核心方法应该是exchange(),这个方法会阻塞直到另一个线程也调用它。可能还有带超时的版本。这里要详细说明方法的使用方式,以及可能抛出的异常,比如中断或超时。 接下来,需要考虑它的实现原理。记得Exchanger使用了类似双重槽位的设计,通过CAS操作来保证线程安全。可能涉及到LockSupport的park和unpark,或者自旋等待。这部分可能需要深入源码分析,但用户可能不需要太底层的细节,但作为超详细介绍,还是得提到。 使用场景方面,除了生产者-消费者,还有线程间数据交换的其他例子,比如游戏服务器中的玩家交易,或者管道化处理的不同阶段交换数据。需要举一些实际的例子,让用户更容易理解。 注意事项方面,线程数超过两个的情况,Exchanger可能不适用,会出问题。另外,exchange()的调用时机需要协调,否则可能线程一直阻塞。还要提醒处理中断和超时的情况,避免程序挂死。 可能用户是正在学习Java并发编程的开发者,需要实际应用Exchanger解决问题,或者面试中遇到相关问题。需要给出一个简单的代码示例,比如两个线程交换字符串,这样直观明了。 还要比较Exchanger和其他同步工具的区别,比如和SynchronousQueue的不同。SynchronousQueue是传递数据,而Exchanger是双向交换,这可能容易混淆,需要澄清。 总结的时候,要强调Exchanger的适用场景和限制,帮助用户判断何时使用。另外,提醒线程间协作的必要性,以及正确使用的重要性,避免常见错误。</think>JUC之Exchanger超详细解析(附核心源码分析) Exchanger是Java并发包(java.util.concurrent)中用于两个线程间交换数据的同步工具类。以下是分步骤详解: 一、核心特性 1. 双向数据交换 - 仅支持两个线程间的数据交换(❗超过两个线程会抛出异常) - 线程A调用exchange()时会阻塞,直到线程B也调用exchange() - 数据交换完成后,双方线程继续执行 2. 方法签名 ```java public V exchange(V x) throws InterruptedException public V exchange(V x, long timeout, TimeUnit unit) throws InterruptedException, TimeoutException ``` 二、底层实现原理(基于JDK17) 1. 核心数据结构 ```java private static final class Node { int index; // 索引编号 int bound; // 边界值 int collides; // CAS失败次数 int hash; // 伪随机数 Object item; // 当前线程携带的数据 volatile Object match; // 配对线程返回的数据 volatile Thread parked; // 挂起的线程 } ``` 2. 交换流程 - 使用`Slot`数组实现多参与者模式(避免竞争) - 采用CAS+自旋实现无锁化操作 - 当发生哈希冲突时,通过`bound`和`collides`字段进行扩容控制 三、使用场景示例 ```java // 生产者-消费者模型 Exchanger<String> exchanger = new Exchanger<>(); // 生产者线程 new Thread(() -> { try { String data = "Product-"+System.currentTimeMillis(); String received = exchanger.exchange(data); System.out.println("Producer received: " + received); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }).start(); // 消费者线程 new Thread(() -> { try { String data = "Money-$100"; String received = exchanger.exchange(data); System.out.println("Consumer received: " + received); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }).start(); ``` 四、关键注意事项 1. 线程数量限制 - 严格仅支持两个线程交换数据 - 第三个线程调用exchange()会导致`IllegalStateException` 2. 超时控制 - 建议使用带超时的exchange方法 - 防止线程永久阻塞(默认最大等待时间约273年) 3. 中断处理 - 当线程被中断时抛出InterruptedException - 需要正确处理中断状态 五、性能优化技巧 1. 避免频繁创建 - Exchanger实例可重复使用 - 初始化成本较高(涉及内部数组的创建) 2. 对象复用 - 尽量复用交换对象(减少GC压力) - 推荐使用不可变对象 六、与SynchronousQueue对比 | 特性 | Exchanger | SynchronousQueue | |--------------------|-------------------|------------------| | 数据方向 | 双向交换 | 单向传递 | | 线程数量 | 严格两个 | 多个生产/消费者 | | 数据结构 | 无缓冲 | 可选公平策略 | | 适用场景 | 对等数据交换 | 生产-消费管道 | 七、源码级优化点 1. 消除伪共享 - 使用`@jdk.internal.vm.annotation.Contended`注解 - 对Node类进行缓存行填充(避免CPU缓存失效) 2. 哈希算法优化 ```java // 使用Marsaglia XorShift随机数算法 private static final int getProbe() { return ThreadLocalRandom.current().nextInt(); } ``` 常见问题解决方案: 1. 线程阻塞问题 - 使用`exchange(V x, long timeout, TimeUnit unit)`方法 - 设置合理的超时阈值 2. 数据竞争问题 - 建议交换不可变对象 - 如果必须使用可变对象,需要额外同步机制 适用场景建议: ✅ 游戏服务器玩家交易系统 ✅ 双线程数据校验核对 ✅ 管道式处理中间交换 ❌ 高吞吐量数据交换(推荐使用Disruptor)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值