Java ReEntrantLock 之 Condition條件(Java代碼實戰-002)

來源:互聯網
上載者:User

標籤:list   ant   線程   函數   ted   ==   容器   string   發送   

 

import java.util.LinkedList;import java.util.concurrent.locks.Condition;import java.util.concurrent.locks.Lock;import java.util.concurrent.locks.ReentrantLock;/** * ConditionTest * 一個測試類別,用Condition實現的生產者消費者問題 */public class ConditionTest {    /* 定義一個容器(鏈表、隊列) */    private LinkedList<String> buffer;    /* 容器可以容納元素的最大數量,通過建構函式來初始化 */    private int maxSize;    private Lock lock;    private Condition fullCondition;    private Condition notFullCondition;    ConditionTest(int maxSize) {        this.maxSize = maxSize;        buffer = new LinkedList<String>();        lock = new ReentrantLock();        fullCondition = lock.newCondition();        notFullCondition = lock.newCondition();    }    /**     * 向容器中放入Element     */    public void set(String string) throws InterruptedException {        // 擷取鎖        lock.lock();        try {            while (maxSize == buffer.size()) {                // 滿了,添加的線程進入等待狀態                notFullCondition.await();            }            buffer.add(string);            // 容器不為空白時,則給等待的讀取的線程發送訊號以便喚醒這些線程進行讀取            fullCondition.signal();        } finally {            lock.unlock();        }    }    /**     * 從容器中擷取Element     */    public String get() throws InterruptedException {        String string;        lock.lock();        try {            while (buffer.size() == 0) {                // 如果容器為空白,則讀取的線程進入等待狀態                fullCondition.await();            }            string = buffer.poll();            // 給寫入的線程發送訊號以便喚醒這些線程來往容器中寫入            notFullCondition.signal();        } finally {            lock.unlock();        }        return string;    }}

 

Java ReEntrantLock 之 Condition條件(Java代碼實戰-002)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.