码迷,mamicode.com
首页 > 其他好文 > 详细

Exchanger

时间:2018-07-13 19:07:48      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:pool   public   ima   就是   .com   out   另一个   over   线程   

Exchanger 用于两个线程之间交换数据,举例;

package com.hts;

import java.util.concurrent.Exchanger;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ExchangerTest {
    class Product implements Runnable{
        Exchanger<Integer> exchanger ;
        Product(Exchanger<Integer> exchanger ){
            this.exchanger = exchanger;
        }
        @Override
        public void run() {
            int data;
            for(int i = 1;i<11;i++){
                data = i;
                System.out.println("Product"+i+"交换前:" + data);
                try {
                    data = exchanger.exchange(data);
                    System.out.println("Product"+i+"交换后:" + data);
                    System.out.println();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    class Consumer implements Runnable{
        Exchanger<Integer> exchanger ;
        Consumer(Exchanger<Integer> exchanger ){
            this.exchanger = exchanger;
        }
        @Override
        public void run() {
            int data = 0;
            for(int i = 1;i<11;i++){
                data = 0;
                System.out.println("Consumer"+i+"交换前:" + data);
                try {
                    data = exchanger.exchange(data);
                    System.out.println("Consumer"+i+"交换后:" + data);
                    System.out.println();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        Exchanger<Integer> exchanger = new Exchanger<>();
        ExecutorService executorService = Executors.newFixedThreadPool(2);
        executorService.submit(new ExchangerTest().new Product(exchanger));
        executorService.submit(new ExchangerTest().new Consumer(exchanger));
    }
}

执行结果:
技术分享图片

大概意思就是一个线程交换的数字是从1-10,而另一个线程则每次交换的数据都是0,可以看出这个exchanger.exchange(data);方法是一个阻塞方法,当一个线程等待交换时,一定会u等到另一个线程也执行exchanger.exchange(data)同时进行交换,交换后才会继续往下执行。

Exchanger

标签:pool   public   ima   就是   .com   out   另一个   over   线程   

原文地址:https://www.cnblogs.com/hts-technology/p/9306495.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!