[英]Multiple Producer and Consumer Multithreading Java Not Working as Intended
我正在研究 Java 的生產者-消費者問題的多生產者和消費者用例。 代碼在github上。 相同的實現適用於單個生產者消費者用例,但對於多生產者消費者用例表現得怪異。
我對 output 有一些疑問:
一開始,所有生產者和一個消費者都有鎖:
Producer t1 has lock
t5 produced 1, integerQueue: [1]
Producer t5 notifiedAll
運行一段時間后,又出現了一個奇怪的現象:
Producer t5 has lock
t5 produced 10, integerQueue: [8, 9, 10]
Producer t5 notifiedAll
Producer t5 has lock
t5 produced 11, integerQueue: [8, 9, 10, 11]
Producer t5 notifiedAll
Consumer t8 has lock
t8 consumed 8, integerQueue: [9, 10, 11]
Consumer t8 notified All
Consumer t8 has lock
t8 consumed 9, integerQueue: [10, 11]
Consumer t8 notified All
任何幫助是極大的贊賞。
您正在使用Producer5
可運行的單個實例並將其多次提交給執行服務。
Producer5 producer = new Producer5(queue, maxCapacity);
pool.execute(producer);
pool.execute(producer);
pool.execute(producer);
pool.execute(producer);
pool.execute(producer);
因此,您在該單個Producer5
實例中的threadName
字段將被覆蓋多次並且沒有用(它將不再打印出實際運行的線程的名稱,此外,它需要是volatile
才能被多個正確更新線程——對於一些正確的定義)。
System.out.println(String.format("\nProducer %s has lock",
threadName // this will be the name of the last thread that entered `run`,
// they all share the same instance
));
如果同一Runnable
實例包含可變的 state,請不要重復使用它。 為每個執行線程創建一個單獨的實例。
生產者線程 t1 持有鎖時,消費者線程 t5 是如何獲得鎖的?
它仍然是線程 t1 運行此代碼,但threadName
字段同時已由線程 t5 更新。 高度誤導 output。
似乎除了一個生產者和消費者之外的所有線程都已死亡,而這兩個線程正在相互切換鎖。
線程都還活着,但只有兩個threadName
字段存在,線程一直在輪流更新(在run
方法的頂部),最終確定了一些值。 所有線程現在只打印該值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.