Exchanger讲解

    同步辅助工具类中的Exchanger的作用是在成对的线程之间相互传递消息,通过exchange()方法进行交换数据。例如如下示例:

public class TestExchanger {

    public static void main(String[] args) throws InterruptedException {
        Exchanger<People> exchanger=new Exchanger<>();
        Thread t1=new Thread(new TestExchangerThread(new People("小明",10),exchanger,0),"小明线程 ");
        Thread t2=new Thread(new TestExchangerThread(new People("小红",20),exchanger,10),"小红线程 ");

        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println("主线程完毕");
    }
}

class TestExchangerThread implements Runnable{

    private Exchanger<People> exchanger;

    private int seconds;

    private People people;

    public TestExchangerThread(People people,Exchanger<People> exchanger,int seconds) {
        this.people = people;
        this.exchanger=exchanger;
        this.seconds=seconds;
    }

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+"得到交换之前的值为"+people);
        try {
            if(seconds>0){
                TimeUnit.SECONDS.sleep(seconds);
            }
            People exchange = exchanger.exchange(people);
            System.out.println(Thread.currentThread().getName()+"得到交换之后的值为"+exchange);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
} 

 这个例子中的exchanger.exchange()方法是一个同步点,如果其他的线程没有到达这个同步点就会阻塞当前线程。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值