java holdsLock()方法檢測一個線程是否擁有鎖

http://blog.csdn.net/w410589502/article/details/54949506java

 

java.lang.Thread中有一個方法叫holdsLock(),它返回true若是當且僅當當前線程擁有某個具體對象的鎖ide

Object o = new Object();
@Test
public void test1() throws Exception {
    new Thread(new Runnable() {
        @Override
        public void run() {
            synchronized(o) {
                System.out.println("child thread: holdLock: " + 
                    Thread.holdsLock(o));
            }
        }
    }).start();
    System.out.println("main thread: holdLock: " + Thread.holdsLock(o));
    Thread.sleep(2000);
}

main thread: holdLock: false
child thread: holdLock: truespa

相關文章
相關標籤/搜索