Exchanger两个线程之间的数据交换

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

/**
 * 实现两个线程之间的数据交换,第一个先拿出数据的线程将一直等待第二个线程拿着数据来到时才能彼此交换
 * @author wualong
 * @date 2017-6-1
 */
public class ExchangerTest {
	public static void main(String[] args) {
		ExecutorService service = Executors.newCachedThreadPool();
		final Exchanger exchanger = new Exchanger();
		
		service.execute(new Runnable() {
			@Override
			public void run() {
				try {
					String dataOne ="wualong";
					System.out.println(Thread.currentThread().getName()+"正在把"+dataOne+"替换出去");
					Thread.sleep(new Random().nextInt(10000));
					String changeData = exchanger.exchange(dataOne);
					System.out.println(Thread.currentThread().getName()+"替换后的数据为:"+changeData);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		});
		
		service.execute(new Runnable() {
			@Override
			public void run() {
				try {
					String dataOne ="wenxiaodie";
					System.out.println(Thread.currentThread().getName()+"正在把"+dataOne+"替换出去");
					Thread.sleep(new Random().nextInt(10000));
					String changeData = exchanger.exchange(dataOne);
					System.out.println(Thread.currentThread().getName()+"替换后的数据为:"+changeData);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		});
	}
}


你可能感兴趣的:(java多线程)