Rumah > Soal Jawab > teks badan
public class ReentrantLockDemo {
private Lock lock = new ReentrantLock();
public void doSomeThing() {
System.out.println(Thread.currentThread().getName()+"是否获得了锁:"+lock.tryLock());
lock.lock();
try {
System.out.println(Thread.currentThread().getName());
Thread.sleep(3000);
} catch (Exception e) {
} finally {
System.out.println(Thread.currentThread().getName()+"释放了锁");
lock.unlock();
}
}
static class MyRunable implements Runnable {
private ReentrantLockDemo demo;
public MyRunable(ReentrantLockDemo demo) {
this.demo = demo;
}
@Override
public void run() {
demo.doSomeThing();
}
}
public static void main(String[] args) throws InterruptedException {
ReentrantLockDemo demo = new ReentrantLockDemo();
new Thread(new MyRunable(demo)).start();
Thread.sleep(1000);
new Thread(new MyRunable(demo)).start();
}
}
输出:
Thread-0是否获得了锁:true
Thread-0
Thread-1是否获得了锁:false
Thread-0释放了锁
然后就卡在这里了。没有任何结果。可能是发生了死锁。
如果我去掉这句话,一切就是正常的:System.out.println(Thread.currentThread().getName()+"是否获得了锁:"+lock.tryLock());
请问这是为什么?
ringa_lee2017-04-18 10:49:22
Anda menggunakan kunci masuk semula Apabila Thread0 memanggil tryLock
, jika kunci semasa tersedia, ia akan memperoleh kunci itu dengan serta-merta lock
kunci reentrant adalah sama dengan 2, jadi apabila Thread0 melepaskan kunci, ia mengambil masa state
dua kali sebelum kunci dilepaskan. unlock