84669 person learning
152542 person learning
20005 person learning
5487 person learning
7821 person learning
359900 person learning
3350 person learning
180660 person learning
48569 person learning
18603 person learning
40936 person learning
1549 person learning
1183 person learning
32909 person learning
今天看博客看到这样一句话:
在java.lang.Thread中有一个方法叫holdsLock(),它返回true如果当且仅当当前线程拥有某个具体对象的锁。
感觉很惊喜,因为写了不少线程但从来不知道有这个方法,于是想写个Demo测试一番,但是发现怎么都写不出来,有前辈可以给个小栗子说明下这个方法该怎么用吗?
人生最曼妙的风景,竟是内心的淡定与从容!
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
This method is designed to allow a program to assert that the current thread already holds a specified lock:
assert Thread.holdsLock(obj);
官方DOC里的话
This method is designed to allow a program to assert that the current thread already holds a specified lock:
官方DOC里的话