并发 - Java:Thread的holdsLock()这个方法该怎么用呢?
黄舟
黄舟 2017-04-17 15:43:38
0
2
884

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

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

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

黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

reply all(2)
迷茫
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
PHPzhong

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

assert Thread.holdsLock(obj);

官方DOC里的话

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!