JDK1.5 Exchange 两个线程互换数据

阅读更多

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

/**
 * Exchange 2个线程之间交换数据 
 */
public class ExchangeTest {

	/**
	 * @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() {
				try {
					String data1="zxx";
					System.out.println("线程"+Thread.currentThread().getName()+"正在把数据"+data1+"换出去");
					Thread.sleep((long)Math.random()*10000);
					String data2=(String)exchanger.exchange(data1);
					System.out.println("线程"+Thread.currentThread().getName()+"换回的数据为"+data2);
				} catch (Exception e) {
					// TODO: handle exception
				}
			}
			
		});
		
		
		service.execute(new Runnable(){
			@Override
			public void run() {
				try {
					String data1="lhm";
					System.out.println("线程"+Thread.currentThread().getName()+"正在把数据"+data1+"换出去");
					Thread.sleep((long)Math.random()*10000);
					String data2=(String)exchanger.exchange(data1);
					System.out.println("线程"+Thread.currentThread().getName()+"换回的数据为"+data2);
				} catch (Exception e) {
					// TODO: handle exception
				}
				
			}
			
		});
		
		service.execute(new Runnable(){
			@Override
			public void run() {
				try {
					String data1="happy";
					System.out.println("线程"+Thread.currentThread().getName()+"正在把数据"+data1+"换出去");
					Thread.sleep((long)Math.random()*10000);
					String data2=(String)exchanger.exchange(data1);
					System.out.println("线程"+Thread.currentThread().getName()+"换回的数据为"+data2);
				} catch (Exception e) {
					// TODO: handle exception
				}
				
			}
			
		});

	}
}


结果:

线程pool-1-thread-1正在把数据zxx换出去
线程pool-1-thread-2正在把数据lhm换出去
线程pool-1-thread-3正在把数据happy换出去
线程pool-1-thread-3换回的数据为zxx
线程pool-1-thread-1换回的数据为happy

你可能感兴趣的:(exchange)