直接看代码吧
1package exchange; 2 3import java.util.concurrent.Exchanger; 4 5/** 6 * Exchanger让两个线程可以互换信息。 7 * 例子中服务生线程往空的杯子里倒水,顾客线程从装满水的杯子里喝水, 8 * 然后通过Exchanger双方互换杯子,服务生接着往空杯子里倒水,顾客接着喝水, 9 * 然后交换,如此周而复始。 10 */ 11public class ExchangerTest { 12 13 // 描述一个装水的杯子 14 public static class Cup{ 15 // 标识杯子是否有水 16 private boolean full = false; 17 public Cup(boolean full){ 18 this.full = full; 19 } 20 // 添水,假设需要5s 21 public void addWater(){ 22 if (!this.full){ 23 try { 24 Thread.sleep(5000); 25 } catch (InterruptedException e) { 26 } 27 this.full = true; 28 } 29 } 30 // 喝水,假设需要10s 31 public void drinkWater(){ 32 if (this.full){ 33 try { 34 Thread.sleep(10000); 35 } catch (InterruptedException e) { 36 } 37 this.full = false; 38 } 39 } 40 } 41 42 public static void testExchanger() { 43 // 初始化一个Exchanger,并规定可交换的信息类型是杯子 44 final Exchanger<Cup> exchanger = new Exchanger<Cup>(); 45 // 初始化一个空的杯子和装满水的杯子 46 final Cup initialEmptyCup = new Cup(false); 47 final Cup initialFullCup = new Cup(true); 48 49 //服务生线程 50 class Waiter implements Runnable { 51 public void run() { 52 Cup currentCup = initialEmptyCup; 53 try { 54 int i=0; 55 while (i < 2){ 56 System.out.println("服务生开始往杯子中添水:" 57 + System.currentTimeMillis()); 58 // 往空的杯子里加水 59 currentCup.addWater(); 60 System.out.println("服务生添水完毕:" 61 + System.currentTimeMillis()); 62 // 杯子满后和顾客的空杯子交换 63 System.out.println("服务生等待与顾客交换杯子:" 64 + System.currentTimeMillis()); 65 currentCup = exchanger.exchange(currentCup); 66 System.out.println("服务生与顾客交换杯子完毕:" 67 + System.currentTimeMillis()); 68 i++; 69 } 70 71 } catch (InterruptedException ex) { 72 } 73 } 74 } 75 76 //顾客线程 77 class Customer implements Runnable { 78 public void run() { 79 Cup currentCup = initialFullCup; 80 try { 81 int i=0; 82 while (i < 2){ 83 System.out.println("顾客开始喝水:" 84 + System.currentTimeMillis()); 85 //把杯子里的水喝掉 86 currentCup.drinkWater(); 87 System.out.println("顾客喝水完毕:" 88 + System.currentTimeMillis()); 89 //将空杯子和服务生的满杯子交换 90 System.out.println("顾客等待与服务生交换杯子:" 91 + System.currentTimeMillis()); 92 currentCup = exchanger.exchange(currentCup); 93 System.out.println("顾客与服务生交换杯子完毕:" 94 + System.currentTimeMillis()); 95 i++; 96 } 97 } catch (InterruptedException ex) { 98 } 99 } 100 } 101 102 new Thread(new Waiter()).start(); 103 new Thread(new Customer()).start(); 104 } 105 106 public static void main(String[] args) { 107 ExchangerTest.testExchanger(); 108 } 109}