search

Home  >  Q&A  >  body text

并发 - Java:Thread的holdsLock()这个方法该怎么用呢?

今天看博客看到这样一句话:

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

感觉很惊喜,因为写了不少线程但从来不知道有这个方法,于是想写个Demo测试一番,但是发现怎么都写不出来,有前辈可以给个小栗子说明下这个方法该怎么用吗?

黄舟黄舟2788 days ago894

reply all(2)I'll reply

  • 迷茫

    迷茫2017-04-17 15:45:38

    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

    reply
    0
  • PHPz

    PHPz2017-04-17 15:45:38

    This method is designed to allow a program to assert that the current thread already holds a specified lock:

    assert Thread.holdsLock(obj);

    官方DOC里的话

    reply
    0
  • Cancelreply