2015-04-03 78 views
0
package threads; 

import java.util.concurrent.locks.Lock; 
import java.util.concurrent.locks.ReentrantLock; 


public class text implements Runnable { 
    static Lock lock = new ReentrantLock(); 

    public static void main(String[] args) throws InterruptedException { 

     testts(); 
     new Thread(new text()).start(); 

    } 

    static void testts() { 
     lock.lock(); 
    } 

    @Override 
    public void run() { 
     lock.unlock(); 

     System.out.println("un-locked"); 
    } 
} 

拋出我的代碼拋出java.lang.IllegalMonitorStateException

Exception in thread "Thread-0" java.lang.IllegalMonitorStateException 
    at java.util.concurrent.locks.ReentrantLock$Sync.tryRelease(ReentrantLock.java:127) 
    at java.util.concurrent.locks.AbstractQueuedSynchronizer.release(AbstractQueuedSynchronizer.java:1175) 
    at java.util.concurrent.locks.ReentrantLock.unlock(ReentrantLock.java:431) 
    at threads.text.run(text.java:28) 
    at java.lang.Thread.run(Thread.java:619) 
+2

你爲什麼認爲**不應該拋出'IllegalMonitorStateException'? – 2015-04-03 01:08:46

回答

2

javadoc of ReentrantLock#unlock()狀態

如果當前線程不是此鎖的則 IllegalMonitorStateException拋出持有人。

您的新線程沒有鎖,主線程會。因此,當新線程試圖解鎖它不保存的鎖時,會拋出異常。

相關問題