簡體   English   中英

多生產者和消費者多線程 Java 未按預期工作

[英]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
  1. 我認為所有線程都應該爭奪鎖,並且最多應該有一個線程擁有所有時間的鎖? 所有生產者都共享鎖嗎? 生產者線程 t1 持有鎖時,消費者線程 t5 是如何獲得鎖的?

運行一段時間后,又出現了一個奇怪的現象:

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
  1. 似乎除了一個生產者和消費者之外的所有線程都已死亡,而這兩個線程正在相互切換鎖。 為什么會這樣? 所有其他生產者和消費者發生了什么?

任何幫助是極大的贊賞。

您正在使用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM