目錄
- 1.ReentrantLock可重入鎖概述
- 2.可重入
- 3.可打斷
- 4.鎖超時
- 5.公平鎖
- 6.條件變數 Condition
1.ReentrantLock可重入鎖概述
相對于 synchronized 它具備如下特點
可中斷
synchronized鎖加上去不能中斷,a執行緒應用鎖,b執行緒不能取消掉它
可以設定超時時間
synchronized它去獲取鎖時,如果對方持有鎖,那么它就會進入entryList一直等待下去,而可重入鎖可以設定超時時間,規定時間內如果獲取不到鎖,就放棄鎖
可以設定為公平鎖
防止執行緒饑餓的情況,即先到先得,如果爭搶的人比較多,則可能會發生永遠都得不到鎖
支持多個條件變數多個waitset(不支持條件一的去a不支持條件二的去b)
synchronized只支持同一個waitset.
與 synchronized 一樣,都支持可重入
基本語法
// 獲取鎖
reentrantLock.lock();
try {
// 臨界區
} finally {
// 釋放鎖
reentrantLock.unlock();
}
synchronized是在關鍵字的級別來保護臨界區,而reentrantLock是在物件的級別保護臨界區,臨界區即訪問共享資源的那段代碼,finally中表明不管將來是否出現例外,都會釋放鎖,釋放鎖即呼叫unlock方法,否則無法釋放鎖,其它執行緒就永遠也獲取不了鎖,
2.可重入
可重入是指同一個執行緒如果首次獲得了這把鎖,那么因為它是這把鎖的擁有者,因此有權利再次獲取這把鎖
如果是不可重入鎖,那么第二次獲得鎖時,自己也會被鎖擋住
ReentrantLock和synchronized都是可重入鎖,
public class TestReentranLock1 {
static ReentrantLock lock = new ReentrantLock();
public static void main(String[] args) {
method1();
}
public static void method1() {
lock.lock();
try {
System.out.println("execute method1");
method2();
} finally {
lock.unlock();
}
}
public static void method2() {
lock.lock();
try {
System.out.println("execute method2");
method3();
} finally {
lock.unlock();
}
}
public static void method3() {
lock.lock();
try {
System.out.println("execute method3");
} finally {
lock.unlock();
}
}
}
execute method1
execute method2
execute method3
3.可打斷
可打斷是指在等待鎖的程序中,其它執行緒可以用interrupt方法終止我的等待,synchronized鎖是不可打斷的,
我們要想在等鎖的程序中被打斷,就要使用lockInterruptibly()方法對lock物件加鎖,而不是lock()方法
public class TestReentranLock2 {
public static void main(String[] args) {
ReentrantLock lock = new ReentrantLock();
Thread t1 = new Thread(() -> {
try {
//如果沒有競爭,此方法就會獲取lock物件的鎖
//如果有競爭,就進入阻塞佇列等待,可以被其它執行緒用interrupt打斷
System.out.println("嘗試獲得鎖");
lock.lockInterruptibly();
} catch (InterruptedException e) {
e.printStackTrace();
System.out.println("等鎖的程序中被打斷");
return;
}
try {
System.out.println("t1獲得了鎖");
} finally {
lock.unlock();
}
}, "t1");
lock.lock();
System.out.println("主執行緒獲得了鎖");
t1.start();
try {
try {
sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
t1.interrupt();
System.out.println("執行打斷t1");
} finally {
lock.unlock();
}
}
}
主執行緒獲得了鎖
嘗試獲得鎖
執行打斷t1
等鎖的程序中被打斷
java.lang.InterruptedException
at java.util.concurrent.locks.AbstractQueuedSynchronizer.doAcquireInterruptibly(AbstractQueuedSynchronizer.java:898)
at java.util.concurrent.locks.AbstractQueuedSynchronizer.acquireInterruptibly(AbstractQueuedSynchronizer.java:1222)
at java.util.concurrent.locks.ReentrantLock.lockInterruptibly(ReentrantLock.java:335)
at cn.yj.jvm.TestReentranLock2.lambda$main$0(TestReentranLock2.java:15)
at java.lang.Thread.run(Thread.java:748)
注意如果是不可中斷模式,那么即使使用了 interrupt 也不會讓等待中斷,即不是,即使用lock()方法,
這種方式可以避免死鎖情況的發生,避免無休止的等待,
ReentrantLock lock = new ReentrantLock();
Thread t1 = new Thread(() -> {
System.out.println("啟動...");
lock.lock();
try {
System.out.println("獲得了鎖");
} finally {
lock.unlock();
}
}, "t1");
lock.lock();
System.out.println("獲得了鎖");
t1.start();
try {
sleep(1);
t1.interrupt();
System.out.println("執行打斷");
sleep(1);
} finally {
System.out.println("釋放了鎖");
lock.unlock();
}
4.鎖超時
ReentranLock支持可打斷,其實就是為了避免死等,這樣就可以減少死鎖的發生,實際上可打斷這種方式屬于一種被動的避免死等,是由其它執行緒interrupt來打斷,
而鎖超時是主動的方式避免死等的手段,
獲取鎖用tryLock()方法,即嘗試獲得鎖,如果成功了,它就獲得鎖,如果失敗了,它就可以不去進入阻塞佇列等待,它就會回傳false,表示沒有獲得鎖,
立刻失敗
public static void main(String[] args) {
ReentrantLock lock = new ReentrantLock();
Thread t1 = new Thread(() -> {
System.out.println("啟動...");
if (!lock.tryLock()) {
System.out.println("獲取不到鎖,立刻失敗,回傳");
return;
}
try {
System.out.println("獲得了鎖");
} finally {
lock.unlock();
}
}, "t1");
lock.lock();
System.out.println("獲得了鎖");
t1.start();
try {
try {
sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
} finally {
lock.unlock();
}
}
獲得了鎖
啟動...
獲取不到鎖,立刻失敗,回傳
超時失敗
lock.tryLock(1,TimeUnit.SECONDS)表示嘗試等待1s,如果主執行緒不釋放鎖,那么它就會回傳false,如果釋放了鎖,那么它就會回傳true.tryLock也支持被打斷,被打斷時報例外,
ReentrantLock lock = new ReentrantLock();
Thread t1 = new Thread(() -> {
log.debug("啟動...");
try {
if (!lock.tryLock(1, TimeUnit.SECONDS)) {
log.debug("獲取等待 1s 后失敗,回傳");
return;
}
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
log.debug("獲得了鎖");
} finally {
lock.unlock();
}
}, "t1");
lock.lock();
log.debug("獲得了鎖");
t1.start();
try {
sleep(2);
} finally {
lock.unlock();
}
輸出
18:19:40.537 [main] c.TestTimeout - 獲得了鎖
18:19:40.544 [t1] c.TestTimeout - 啟動...
18:19:41.547 [t1] c.TestTimeout - 獲取等待 1s 后失敗,回傳
5.公平鎖
對于synchronized來說,它是不公平的鎖,當一個執行緒持有鎖,其他執行緒就會進入阻塞佇列等待,當鎖的持有者釋放鎖的時候,這些執行緒就會一擁而上,誰先搶到,誰就成為monitor的主人,而不會按照先來先得的規則,
ReentrantLock 默認是不公平的
ReentrantLock有一個帶參構造方法,默認是非公平的,
public ReentrantLock(boolean fair) {
sync = fair ? new FairSync() : new NonfairSync();
}
我們可以通過布林值改成真,來保證它的公平性,即將來阻塞佇列里的執行緒,爭搶鎖的時候會按照進入阻塞佇列的順序執行,先到先得,
6.條件變數 Condition
synchronized 中也有條件變數,就是我們講原理時那個 waitSet 休息室,當條件不滿足時進入 waitSet 等待
ReentrantLock 的條件變數比 synchronized 強大之處在于,它是支持多個條件變數的,這就好比
synchronized 是那些不滿足條件的執行緒都在一間休息室等訊息
而 ReentrantLock 支持多間休息室,有專門等煙的休息室、專門等早餐的休息室、喚醒時也是按休息室來喚醒
使用要點:
- await 前需要獲得鎖
- await 執行后,會釋放鎖,進入 conditionObject 等待
- await 的執行緒被喚醒(或打斷、或超時)取重新競爭 lock 鎖
- 競爭 lock 鎖成功后,從 await 后繼續執行
- signal 相當于 notify,signalAll 相當于 notifyAll
static ReentrantLock lock = new ReentrantLock();
static Condition waitCigaretteQueue = lock.newCondition();
static Condition waitbreakfastQueue = lock.newCondition();
static volatile boolean hasCigrette = false;
static volatile boolean hasBreakfast = false;
public static void main(String[] args) {
new Thread(() -> {
try {
lock.lock();
while (!hasCigrette) {
try {
waitCigaretteQueue.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
log.debug("等到了它的煙");
} finally {
lock.unlock();
}
}).start();
new Thread(() -> {
try {
lock.lock();
while (!hasBreakfast) {
try {
waitbreakfastQueue.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
log.debug("等到了它的早餐");
} finally {
lock.unlock();
}
}).start();
sleep(1);
sendBreakfast();
sleep(1);
sendCigarette();
}
private static void sendCigarette() {
lock.lock();
try {
log.debug("送煙來了");
hasCigrette = true;
waitCigaretteQueue.signal();
} finally {
lock.unlock();
}
}
private static void sendBreakfast() {
lock.lock();
try {
log.debug("送早餐來了");
hasBreakfast = true;
waitbreakfastQueue.signal();
} finally {
lock.unlock();
}
}
輸出
18:52:27.680 [main] c.TestCondition - 送早餐來了
18:52:27.682 [Thread-1] c.TestCondition - 等到了它的早餐
18:52:28.683 [main] c.TestCondition - 送煙來了
18:52:28.683 [Thread-0] c.TestCondition - 等到了它的煙
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/257439.html
標籤:java
上一篇:執行緒池的常用知識
