java线程中Exchanger使用

有时我们须要对元素进行配对和交换线程的同步点,使用exchange方法 返回其伙伴的对象,这时我们就须要使用线程类中的Exchanger类了,

我通过一个实例 来简单说明一下他的用法及其作用:

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


public class TestExchanger {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
         ExecutorService executor = Executors.newCachedThreadPool();
         final Exchanger<String> exchanger = new Exchanger<String>();
         executor.execute(new Runnable() {
			String data1 = "abc";
 			@Override
			public void run() {
				try {
					System.out.println(Thread.currentThread().getName() +"正在把数据 "+ data1+ " 交换出去" );
					Thread.sleep((long) (Math.random()*1000));
					
					String data2 = (String) exchanger.exchange(data1);
					System.out.println(Thread.currentThread().getName() + "交换数据 到  "+ data2);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		});
         
         executor.execute(new Runnable() {
        	 String data1 = "def";
			@Override
			public void run() {
				try {
					System.out.println(Thread.currentThread().getName() +"正在把数据 "+ data1+ " 交换出去" );
					Thread.sleep((long) (Math.random()*1000));
					
					String data2 = (String) exchanger.exchange(data1);
					System.out.println(Thread.currentThread().getName() + "交换数据 到  "+ data2);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		});
	}

}

运行完毕之后;你会发现数据完毕交换

pool-1-thread-1正在把数据 abc 交换出去
pool-1-thread-2正在把数据 def 交换出去
pool-1-thread-2交换数据 到  abc
pool-1-thread-1交换数据 到  def

    原文作者:zhchoutai
    原文地址: http://www.cnblogs.com/zhchoutai/p/6819451.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞