多線程編程中wait()方法拋出IllegalMonitorStateException異常的解析
本文分析一個多線程編程問題:三個線程(a、b、c)按順序打印ID五次(abcabc…),使用wait()和notifyAll()方法同步,卻拋出IllegalMonitorStateException異常。
問題描述: 程序使用volatile字符串變量current_thread控制線程執行順序,并用synchronized塊和wait()、notifyAll()方法進行同步。然而,運行時出現IllegalMonitorStateException。
錯誤代碼片段:
// 線程打印完畢后,設置下一個要打印的線程標識,并喚醒其他線程 if (current_thread.equals("a")) { current_thread = "b"; } else if (current_thread.equals("b")) { current_thread = "c"; } else if (current_thread.equals("c")) { current_thread = "a"; }
完整代碼(略有修改,方便理解):
package 并發編程.work2; public class Test { private static volatile String current_thread = "A"; private static final Object lock = new Object();//新增鎖對象 public static void main(String[] args) { Thread t1 = new Thread(new PrintThreadName("A"), "A"); Thread t2 = new Thread(new PrintThreadName("B"), "B"); Thread t3 = new Thread(new PrintThreadName("C"), "C"); t1.start(); t2.start(); t3.start(); } static class PrintThreadName implements Runnable { private String threadName; public PrintThreadName(String threadName) { this.threadName = threadName; } @Override public void run() { for (int i = 0; i < 5; i++) { synchronized (lock) { // 使用獨立鎖對象 while (!current_thread.equals(threadName)) { try { lock.wait(); // 使用獨立鎖對象 } catch (InterruptedException e) { e.printStackTrace(); } } System.out.print(threadName); if (threadName.equals("A")) { current_thread = "B"; } else if (threadName.equals("B")) { current_thread = "C"; } else { current_thread = "A"; } lock.notifyAll(); // 使用獨立鎖對象 } } } } }
異常原因: wait()方法必須在持有對象的監視器鎖時調用。 原代碼中,current_thread作為鎖對象,但在synchronized塊內修改了current_thread的值。當線程調用wait()進入等待,current_thread的引用改變了。喚醒后,線程試圖釋放鎖,但持有的鎖對象已不是當前的current_thread,導致IllegalMonitorStateException。
解決方案: 使用一個獨立的鎖對象(例如代碼中的lock對象)來控制線程同步,避免在持有鎖的同時修改鎖對象本身。 修改后的代碼使用lock對象作為synchronized塊的鎖和wait()、notifyAll()方法的參數,從而避免了異常。 這保證了wait()方法始終在正確的鎖對象上操作。
? 版權聲明
文章版權歸作者所有,未經允許請勿轉載。
THE END