欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2022-05-28 18:23:57
...

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