Java多線程之Exchanger

來源:互聯網
上載者:User
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();}}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.