【JAVA並發編程實戰】12、使用condition實現多線程下的有界緩衝先進先出隊列

來源:互聯網
上載者:User

標籤:current   finally   size   on()   empty   編程   not   nal   cond   

package cn.study.concurrency.ch14;import java.util.concurrent.locks.Condition;import java.util.concurrent.locks.Lock;import java.util.concurrent.locks.ReentrantLock;/** * 使用condition作為掛起線程的訊號 * 這個是先進先出的隊列 * @author xiaof * * @param <T> */public class ConditionBoundedBuffer<T> {    protected final Lock lock = new ReentrantLock();    //資料隊列長度    private static final int BUFFER_SIZE = 1024;    //建立兩個condition,一個代表不為空白,一個代表不滿    private final Condition notFull = lock.newCondition();    private final Condition notEmpty = lock.newCondition();    private final T[] items = (T[]) new Object[BUFFER_SIZE];    private int tail, head, count;        public void put(T x) throws InterruptedException    {        lock.lock();//這裡在進行操作的時候上鎖        try {            while(count == items.length)            {                //如果是滿的就掛起線程,等待變為notFull                notFull.await();            }            items[tail] = x;            //判斷是否是已經達到了滿隊列的情況            if(++tail == items.length)                tail = 0;            //計數值++            ++count;            //插入資料,隊列肯定不是空的,那麼進行非空訊號發布            notEmpty.signal();        } finally{            //執行完畢,切記一定要解鎖            lock.unlock();        }    }        //擷取資料,阻塞直到隊列中有資料為止    public T take() throws InterruptedException    {        lock.lock();//進行操作之前,先上鎖                try {            while(count == 0)            {                //如果隊列中沒有資料,那麼就要進行現場掛起                notEmpty.await();            }            //得到資料,用來返回            T t = items[head];            items[head] = null;//吧輸出出去的資料設為空白            if(++head == items.length)                head = 0; //重設隊裡索引            --count;    //計數減一            notFull.signal();//喚醒插入操作,因為擷取出去一個資料,那麼隊列就一定有空位            return t;        } finally {            //切記在執行完畢之後,不論成功與否,都要解鎖            lock.unlock();        }    }    }

 

【JAVA並發編程實戰】12、使用condition實現多線程下的有界緩衝先進先出隊列

聯繫我們

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