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(); } }