java多线程同步工具之Exchanger

Exchanger用于实现两个人之间的数据交换,每个人在完成一定的事物后想与对方交换数据,第一个先拿出数据的人将一直等待第二个人拿着数据到来时,才能彼此交换数据。


案例:

public class ExchangerTest {

	public static void main(String[] args) {
		/* 创建缓存型线程池 */
		ExecutorService service = Executors.newCachedThreadPool();
		/* 创建爱你Exchanger对象 */
		final Exchanger exchanger = new Exchanger();

		service.execute(new Runnable() {
			public void run() {
				try {

					String data1 = "胡锦涛";
					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) {

				}
			}
		});
		
		service.execute(new Runnable() {
			public void run() {
				try {

					String data1 = "习近平";
					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) {

				}
			}
		});
	}
}

程序运行的结果:

java多线程同步工具之Exchanger_第1张图片

你可能感兴趣的:(Exchanger,线程同步的数据交换)