1 回答

TA貢獻1802條經驗 獲得超5個贊
您正在使用可運行對象的單個實例Producer5,并將其多次提交給執行服務。
Producer5 producer = new Producer5(queue, maxCapacity);
pool.execute(producer);
pool.execute(producer);
pool.execute(producer);
pool.execute(producer);
pool.execute(producer);
因此,threadName該單個實例中的字段Producer5將被覆蓋多次并且沒有用(它將不再打印出實際正在運行的線程的名稱,此外,它需要被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如果同一實例包含可變狀態,請勿重復使用該實例。為每個執行線程創建一個單獨的實例。
當生產者線程 t1 持有鎖時,消費者線程 t5 如何獲得鎖?
仍然是線程 t1 運行此代碼,但該threadName字段同時已由線程 t5 更新。高度誤導性的輸出。
似乎除了一個生產者和消費者之外的所有線程都已死亡,并且這兩個線程正在彼此之間切換鎖。
線程都仍然處于活動狀態,但只有兩個threadName字段存在,線程輪流更新它們(在方法的頂部run),最終確定某個值。所有線程現在只打印該值。
添加回答
舉報