场景:两个线程
功能:两个线程之间的数据交换
案例:
public class ExchangeTest { public static void main(String[] args) { ExecutorService service = Executors.newFixedThreadPool(2); final Exchanger exchanger = new Exchanger(); service.execute(new Runnable(){ public void run() { try { String money = "美钞"; System.out.println("买方" + Thread.currentThread().getName() + "想把" + money +"换出去"); Thread.sleep((long)(Math.random()*10000)); String product = (String)exchanger.exchange(money); System.out.println("买方" + Thread.currentThread().getName() +"买回的是" + product); }catch(Exception e){ System.out.println("交易失败..."); } } }); service.execute(new Runnable(){ public void run() { try { String product = "AK-47"; System.out.println("卖方" + Thread.currentThread().getName() +"正在把" + product +"卖出去"); Thread.sleep((long)(Math.random()*10000)); String money = (String)exchanger.exchange(product); System.out.println("卖方" + Thread.currentThread().getName() + "拿到" + money); }catch(Exception e){ System.out.println("交易失败..."); } } }); service.shutdown(); } }
结果输出:
买方pool-1-thread-1想把美钞换出去
卖方pool-1-thread-2正在把AK-47卖出去
卖方pool-1-thread-2拿到美钞
买方pool-1-thread-1买回的是AK-47