java并发编程(Exchanger)

package org.bianqi.demo1;

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

public class Demo3 {
	public static void main(String[] args) throws InterruptedException, TimeoutException {
		ExecutorService service = Executors.newCachedThreadPool();
		final Exchanger<String> exchanger = new Exchanger<>();
		service.execute(new Runnable() {
			public void run() {
				String data1 = "毒品";
				System.out.println("毒贩子带着"+data1+"出发了");
				try {
					Thread.sleep((long) (Math.random()*1000));
					String exchange = exchanger.exchange(data1,2, TimeUnit.SECONDS);
					System.out.println("毒贩子把"+exchange+"带走了");
				} catch (InterruptedException | TimeoutException e) {
					e.printStackTrace();
				}
			}
		});
		
		service.execute(new Runnable() {
			public void run() {
				String  data2 ="人民币";
				System.out.println("瘾君子带着"+data2+"出发了");
				try {
					Thread.sleep((long) (Math.random()*1000));
					String exchange = exchanger.exchange(data2, 2, TimeUnit.SECONDS);
					System.out.println("瘾君子把"+exchange+"带走了");
				} catch (InterruptedException | TimeoutException e) {
					e.printStackTrace();
				}
			}
		});
		service.shutdown();
	}
}

  

posted @ 2017-03-29 16:46  回眸,境界  阅读(302)  评论(0编辑  收藏  举报