在這里考慮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))。
希望這可以幫助。
添加回答
舉報(bào)
0/150
提交
取消