一.ReentrantLock總結(jié)
1.一些方法:
ReentrantLock reentrantLock = new ReentrantLock();
1)加鎖
reentrantLock.lock();
2)釋放鎖
reentrantLock.unlock();
3)嘗試獲取鎖 獲取不到返回false,獲取不到直接放棄,不進(jìn)入阻塞隊(duì)列
reentrantLock.tryLock();
4)在給定時(shí)間內(nèi)獲取鎖,獲取不到就退出
reentrantLock.tryLock(2, TimeUnit.SECONDS);
5)鎖綁定多個(gè)條件:一個(gè) ReentrantLock 可以同時(shí)綁定多個(gè) Condition 對(duì)象,更細(xì)粒度的喚醒線程,
通過(guò)reentrantLock.newCondition()創(chuàng)建一個(gè)條件變量condition
通過(guò)condition.await()方法,當(dāng)前線程進(jìn)入condition等待,釋放鎖;
通過(guò)condition.singal()方法,喚醒在condition中的線程;
6)reentrantLock.lockInterruptibly()`:獲得可打斷的鎖
public static void main(String[] args) throws InterruptedException {
ReentrantLock lock = new ReentrantLock();
Thread t1 = new Thread(() -> {
try {
System.out.println("嘗試獲取鎖");
lock.lockInterruptibly();
} catch (InterruptedException e) {
System.out.println("沒(méi)有獲取到鎖,被打斷,直接返回");
return;
}
try {
System.out.println("獲取到鎖");
} finally {
lock.unlock();
}
}, "t1");
lock.lock();
t1.start();
Thread.sleep(2000);
System.out.println("主線程進(jìn)行打斷鎖");
t1.interrupt();
}