java学习——使用Exchanger实现两个线程间的数据交换

package com.hujl.thread;

import java.util.concurrent.Exchanger;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
 * 线程之间互换数据
 * @author Janrone
 * @website http://hujl.sinaapp.com
 */
public class ExchangerDemo {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		ExecutorService service=Executors.newCachedThreadPool();
		//线程之间交换数据
		final Exchanger exchanger=new Exchanger();
		
		service.execute(new Runnable() {		
			@Override
			public void run() {
				// TODO Auto-generated method stub
				String data1="data1";
				System.out
						.println("线程"+Thread.currentThread().getName()+"正在把数据交换出去"+data1);
				try {
					Thread.sleep((long)(Math.random()*10000));
					String data2=exchanger.exchange(data1);
					System.out
					.println("线程"+Thread.currentThread().getName()+"换回来的数据"+data2);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
		
		service.execute(new Runnable() {		
			@Override
			public void run() {
				// TODO Auto-generated method stub
				String data1="data2";
				System.out
						.println("线程"+Thread.currentThread().getName()+"正在把数据交换出去"+data1);
				try {
					Thread.sleep((long)(Math.random()*10000));
					String data2=exchanger.exchange(data1);
					System.out
					.println("线程"+Thread.currentThread().getName()+"换回来的数据"+data2);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
		
		service.shutdown();
	}

}

你可能感兴趣的:(java基础)