Java并发编程-同步辅助类之Exchanger

Exchanger是自jdk1.5起开始提供的工具套件,一般用于两个工作线程之间交换数据。在本文中我将采取由浅入深的方式来介绍分析这个工具类。

首先我们来看看官方的api文档中的叙述:
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.
在以上的描述中,有几个要点:

  • 此类提供对外的操作是同步的;
  • 用于成对出现的线程之间交换数据;
  • 可以视作双向的同步队列;
  • 可应用于基因算法、流水线设计等场景。

构造方法:
public Exchanger()
public V exchange(V x) throws InterruptedException
public V exchange(V x, long timeout, TimeUnit unit) throws InterruptedException, TimeoutException

从官方的javadoc可以知道
,如果它的伙伴线程此前已经调用了此方法,那么它的伙伴会被调度唤醒并与之进行对象交换,然后各自返回。如果它的伙伴还没到达交换点,那么当前线程将会被挂起,直至伙伴线程到达——完成交换正常返回;或者当前线程被中断——抛出中断异常;又或者是等候超时——抛出超时异常。

使用例子
下面创建两个生产者线程生产一些序列,然后通过Exchanger进行交换:

package concurrent;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.Exchanger;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

public class ExchangerTest {

    public static void main(String[] args) {
        Exchanger<List<Integer>> exchanger = new Exchanger<>();
        ThreadPoolExecutor executor=(ThreadPoolExecutor) Executors.newCachedThreadPool();
        executor.execute(new Producer(exchanger));
        executor.execute(new Producer(exchanger));
    }

}

class Producer extends Thread {
    List<Integer> list = new ArrayList<>();
    Exchanger<List<Integer>> exchanger = null;
    public Producer(Exchanger<List<Integer>> exchanger) {
        super();
        this.exchanger = exchanger;
    }
    @Override
    public void run() {
        Random rand = new Random();
        int num;
        num=rand.nextInt(10000);
        list.add(num);
        num=rand.nextInt(10000);
        list.add(num);
        num=rand.nextInt(10000);
        list.add(num);
        num=rand.nextInt(10000);
        list.add(num);
        num=rand.nextInt(10000);
        list.add(num);
        try {
            System.out.println(Thread.currentThread().getName()+":交换前:");
            print();
            list = exchanger.exchange(list);
            System.out.println(Thread.currentThread().getName()+":交换后:");
            print();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    public void print(){
        for(Integer i:list){
            System.out.println(i);
        }
    }
}

}

执行结果:
pool-1-thread-1:交换前:
185
3669
9943
4364
7101
pool-1-thread-2:交换前:
1091
1364
7341
3755
4966
pool-1-thread-2:交换后:
185
3669
9943
4364
7101
pool-1-thread-1:交换后:
1091
1364
7341
3755
4966
其他同步辅助类:
Java并发编程-同步辅助类之Phaser
Java并发编程-同步辅助类之CyclicBarrier
Java并发编程-同步辅助类之CountDownLatch
Java并发编程-同步辅助类之Semaphore

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值