java holdsLock()方法检测一个线程是否拥有锁

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

 

java.lang.Thread中有一个方法叫holdsLock(),它返回true如果当且仅当当前线程拥有某个具体对象的锁

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: true

    原文作者:java锁
    原文地址: https://www.cnblogs.com/gxh973121/archive/2018/03/12/8550593.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞