第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

如何避免多生產(chǎn)者和消費(fèi)者中的饑餓?

如何避免多生產(chǎn)者和消費(fèi)者中的饑餓?

慕勒3428872 2021-04-10 14:11:15
在這里考慮2個(gè)生產(chǎn)者線程和1個(gè)消費(fèi)者線程。假設(shè)隊(duì)列已滿。由于隊(duì)列已滿,兩個(gè)生產(chǎn)者線程進(jìn)入等待狀態(tài)。消費(fèi)者線程從隊(duì)列和notifyAll中獲取元素,因此生產(chǎn)者線程中的一個(gè)添加元素并退出,另一個(gè)生產(chǎn)者線程保持等待狀態(tài),另一個(gè)生產(chǎn)者線程再次添加元素并退出。因此,如果您觀察到,則有一個(gè)線程可能始終處于等待狀態(tài)的機(jī)會(huì)。如何避免這種情況?import java.util.LinkedList;import java.util.List;interface BlockingQueueCustom<E> {      void put(E item)  throws InterruptedException ;      E take()  throws InterruptedException;}class LinkedBlockingQueueCustom<E> implements BlockingQueueCustom<E> {    private List<E> queue;    private int maxSize; // maximum number of elements queue can hold at a time.    public LinkedBlockingQueueCustom(int maxSize) {        this.maxSize = maxSize;        queue = new LinkedList<E>();    }    public synchronized void put(E item) throws InterruptedException {         while(queue.size() == maxSize) {            this.wait();        }        queue.add(item);        this.notifyAll();    }    public synchronized E take() throws InterruptedException {        while(queue.size() == 0) {            this.wait();        }        this.notifyAll();        return queue.remove(0);    }}public class BlockingQueueCustomTest {    public static void main(String[] args) throws InterruptedException {        BlockingQueueCustom<Integer> b = new LinkedBlockingQueueCustom<Integer>(10);        System.out.println("put(11)");        b.put(11);        System.out.println("put(12)");        b.put(12);        System.out.println("take() > " + b.take());        System.out.println("take() > " + b.take());    }}
查看完整描述

2 回答

?
蝴蝶不菲

TA貢獻(xiàn)1810條經(jīng)驗(yàn) 獲得超4個(gè)贊

自2005年以來(lái),wait和的使用notify已經(jīng)過(guò)時(shí),因?yàn)樗荒茏鲂┫拗啤?/p>

對(duì)于您的特定問(wèn)題,我真的建議您重構(gòu)解決方案以使用Java Semaphore類。您將看到可以設(shè)置公平性參數(shù)。此參數(shù)將確保以FIFO方式進(jìn)行分配,以便一旦您的一個(gè)線程獲得許可并將數(shù)據(jù)放入您的隊(duì)列后,再次阻塞時(shí),數(shù)據(jù)就被帶到行尾(因此,第二個(gè)線程將獲得優(yōu)先權(quán))。

希望這可以幫助。


查看完整回答
反對(duì) 回復(fù) 2021-04-14
  • 2 回答
  • 0 關(guān)注
  • 182 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)