码迷,mamicode.com
首页 > 编程语言 > 详细

JAVA线程同步辅助类Exchanger-交换

时间:2016-01-13 10:57:50      阅读:166      评论:0      收藏:0      [点我收藏+]

标签:

可以在对中对元素进行配对和交换的线程的同步点。每个线程将条目上的某个方法呈现给 exchange 方法,与伙伴线程进行匹配,并且在返回时接收其伙伴的对象。Exchanger 可能被视为 SynchronousQueue 的双向形式。Exchanger 可能在应用程序(比如遗传算法和管道设计)中很有用。

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

public class ExchangerTest {
    public static void main(String[] args) {
        ExecutorService service = Executors.newCachedThreadPool();
        final Exchanger<String> exchanger = new Exchanger<String>();
        service.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    String data1 = "duwenlei";
                    System.out.println("线程"+Thread.currentThread().getName()+"要换的数据为"+data1);
                    System.out.println("线程"+Thread.currentThread().getName()+"等待对方");
                    Thread.sleep(new Random().nextInt(10000));
                    String data2 = exchanger.exchange(data1);    //开始互换数据
                    System.out.println("线程"+Thread.currentThread().getName()+"互换后的数据为"+data2);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        service.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    String data1 = "shenjing";
                    System.out.println("线程"+Thread.currentThread().getName()+"要换的数据为"+data1 );
                    System.out.println("线程"+Thread.currentThread().getName()+"等待对方");
                    Thread.sleep(new Random().nextInt(10000));
                    String data2 = exchanger.exchange(data1);
                    System.out.println("线程"+Thread.currentThread().getName()+"互换后的数据为"+data2);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        service.shutdown();
    }
}

 

 

JAVA线程同步辅助类Exchanger-交换

标签:

原文地址:http://www.cnblogs.com/duwenlei/p/5126447.html

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