java - 為什么第一個(gè)線程已經(jīng)釋放了鎖,第二個(gè)線程卻不行?
問(wèn)題描述
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;}@Overridepublic 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是否獲得了鎖:trueThread-0Thread-1是否獲得了鎖:falseThread-0釋放了鎖
然后就卡在這里了。沒(méi)有任何結(jié)果。可能是發(fā)生了死鎖。
如果我去掉這句話,一切就是正常的:System.out.println(Thread.currentThread().getName()+'是否獲得了鎖:'+lock.tryLock());
請(qǐng)問(wèn)這是為什么?
問(wèn)題解答
回答1:你用的是可重入鎖,在Thread0在調(diào)用tryLock的時(shí)候,如果當(dāng)前鎖可獲得,會(huì)立刻獲取鎖,后面你又調(diào)用了一次lock,由于Thread0已經(jīng)獲取了鎖,所以可重入鎖的state等于2,所以 Thread0 釋放鎖的時(shí)候要unlock兩次鎖才被真正的釋放掉。
