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> 根据用户查询,我们需要提供关于Java Exchanger的使用方法、原理及示例代码。参考引用内容,我们可以整理出以下信息: 1. **基本概念**:Exchanger是Java并发工具类,用于两个线程之间交换数据。它提供一个同步点,两个线程在同步点交换数据。 2. **使用方法**: - 创建Exchanger实例:`Exchanger<V> exchanger = new Exchanger<>();` - 线程调用`exchange()`方法交换数据,该方法会阻塞直到另一个线程也调用`exchange()`方法。 - 可设置超时的交换:`exchange(V x, long timeout, TimeUnit unit)` 3. **原理**: - 在JDK1.8中,Exchanger采用无锁+分散热点(多槽交换)的方式提升性能,避免伪共享问题。 - 当两个线程都到达同步点时,它们交换数据。 4. **示例代码**:引用[1]提供了一个示例,展示两个线程交换字符串。 我们将按照以下结构组织回答: - 使用指南:包括创建Exchanger和调用exchange方法。 - 原理简述:解释Exchanger的工作机制。 - 完整示例代码:基于引用[1]的示例,稍作调整使其更清晰。 - 注意事项:如线程配对、超时处理等。 同时,根据要求,在回答末尾生成相关问题。 </think>### Java Exchanger 的使用方法、原理及示例代码 #### 一、使用方法 Exchanger 是 Java 并发工具类,用于**两个线程间同步交换数据**。其核心方法如下: ```java // 创建 Exchanger 实例(泛型指定交换数据类型) Exchanger<String> exchanger = new Exchanger<>(); // 线程交换数据(阻塞直到配对线程出现) String receivedData = exchanger.exchange(myData); // 带超时的交换(避免永久阻塞) String receivedData = exchanger.exchange(myData, 100, TimeUnit.SECONDS); ``` **关键特性**: 1. **成对线程**:必须由两个线程成对调用 `exchange()` 方法才能完成交换[^3]。 2. **数据同步点**:交换操作在同步点发生,先到达的线程会阻塞等待另一个线程[^3]。 3. **超时机制**:避免死锁,超时抛出 `TimeoutException`[^1]。 #### 二、实现原理 1. **无锁设计**: - 采用 CAS (Compare-And-Swap) 操作实现线程安全[^2]。 - 类似 `LongAdder` 的分散热点思想,通过多槽(`arena`)减少竞争[^2][^4]。 2. **防伪共享优化**: - 槽位内存按缓存行对齐(`ASHIFT=7` 确保最小 128 字节间隔)[^4]。 3. **动态扩容**: - 初始为单槽交换,高并发时自动扩展为多槽(`arena` 数组)[^2][^4]。 4. **自旋控制**: - 自旋次数由 `SPINS` 常量控制(默认为 1024 次),单核 CPU 禁用自旋[^4]。 #### 三、完整示例代码 ```java import java.util.concurrent.*; public class ExchangerDemo { private static final Exchanger<String> exchanger = new Exchanger<>(); public static void main(String[] args) throws InterruptedException { // 线程1:携带数据 "Data-A" new Thread(() -> exchangeData("Data-A")).start(); // 延迟5秒启动线程2 Thread.sleep(5000); new Thread(() -> exchangeData("Data-B")).start(); } private static void exchangeData(String data) { try { System.out.println(Thread.currentThread().getName() + " 发送数据: " + data); // 阻塞直到配对线程出现 String received = exchanger.exchange(data, 10, TimeUnit.SECONDS); System.out.println(Thread.currentThread().getName() + " 收到数据: " + received); } catch (TimeoutException e) { System.err.println("交换超时!"); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } } ``` **输出结果**: ``` Thread-0 发送数据: Data-A // 线程1阻塞等待 (5秒后) Thread-1 发送数据: Data-B Thread-0 收到数据: Data-B // 线程1继续执行 Thread-1 收到数据: Data-A // 线程2继续执行 ``` #### 四、注意事项 1. **线程配对**:奇数线程调用会导致最后一个线程永久阻塞。 2. **超时设置**:生产环境务必设置超时,避免系统僵死[^1]。 3. **适用场景**:适合**双线程流水线**模型(如生产者-消费者)。 4. **性能考量**:高并发场景优于 `synchronized`,但弱于 `Disruptor` 等无锁队列[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值