import java.util.concurrent.Exchanger;/** * Exchanger讓兩個線程可以互換資訊。 * 例子中服務生線程往空的杯子裡倒水,顧客線程從裝滿水的杯子裡喝水, * 然後通過Exchanger雙方互換杯子,服務生接著往空杯子裡倒水,顧客接著喝水, * 然後交換,如此周而復始。 */public class ExchangerTest {// 描述一個裝水的杯子public static class Cup{// 標識杯子是否有水private boolean full = false;public Cup(boolean full){this.full = full;}// 添水,假設需要5spublic void addWater(){if (!this.full){try {Thread.sleep(5000);} catch (InterruptedException e) {}this.full = true;}}// 喝水,假設需要10spublic void drinkWater(){if (this.full){try {Thread.sleep(10000);} catch (InterruptedException e) {}this.full = false;}}}public static void testExchanger() {//初始化一個Exchanger,並規定可交換的資訊類型是杯子final Exchanger<Cup> exchanger = new Exchanger<Cup>();// 初始化一個空的杯子和裝滿水的杯子final Cup initialEmptyCup = new Cup(false); final Cup initialFullCup = new Cup(true);//服務生線程class Waiter implements Runnable {public void run() {Cup currentCup = initialEmptyCup;try {int i=0;while (i < 2){System.out.println("服務生開始往杯子中添水:"+ System.currentTimeMillis());// 往空的杯子裡加水currentCup.addWater();System.out.println("服務生添水完畢:"+ System.currentTimeMillis());// 杯子滿後和顧客的空杯子交換System.out.println("服務生等待與顧客交換杯子:"+ System.currentTimeMillis());currentCup = exchanger.exchange(currentCup);System.out.println("服務生與顧客交換杯子完畢:"+ System.currentTimeMillis());i++;}} catch (InterruptedException ex) {}}}//顧客線程class Customer implements Runnable {public void run() {Cup currentCup = initialFullCup;try {int i=0;while (i < 2){System.out.println("顧客開始喝水:"+ System.currentTimeMillis());//把杯子裡的水喝掉currentCup.drinkWater();System.out.println("顧客喝水完畢:"+ System.currentTimeMillis());//將空杯子和服務生的滿杯子交換System.out.println("顧客等待與服務生交換杯子:"+ System.currentTimeMillis());currentCup = exchanger.exchange(currentCup);System.out.println("顧客與服務生交換杯子完畢:"+ System.currentTimeMillis());i++;}} catch (InterruptedException ex) {}}}new Thread(new Waiter()).start(); new Thread(new Customer()).start();}public static void main(String[] args) {ExchangerTest.testExchanger();}}