在如何解決原子性問(wèn)題的最后,我們賣了個(gè)關(guān)子,互斥鎖不僅僅只有synchronized關(guān)鍵字,還可以用什么來(lái)實(shí)現(xiàn)呢?
J.U.C包中還提供了一個(gè)叫做Locks的包,我好歹英語(yǔ)過(guò)了四級(jí),聽(tīng)名字我就能馬上大聲的說(shuō):Locks包必然也可以用作互斥!
ReentrantLock
我們可以通過(guò)從具體到抽象的方法來(lái)揭開(kāi)Locks包的神秘面試。

從圖中可以看出,有個(gè)叫做ReentrantLock實(shí)現(xiàn)了Lock接口,那么就從它入手吧!
顧名思義,ReentrantLock叫做可重入鎖,所謂可重入鎖,顧名思義,指的是線程可以重復(fù)獲取同一把鎖。
ReentrantLock也是互斥鎖,因此也可以保證原子性。
先寫(xiě)一個(gè)簡(jiǎn)單的demo上手吧,就拿原子性問(wèn)題中兩個(gè)線程分別做累加的demo為例,現(xiàn)在使用ReentrantLock來(lái)改寫(xiě):
private void add10K() {
// 獲取鎖
reentrantLock.lock();
try {
int idx = 0;
while (idx++ < 10000) {
count++;
}
} finally {
// 保證鎖能釋放
reentrantLock.unlock();
}
}
ReentrantLock在這里可以達(dá)到和synchronized一樣的效果,為了方便你回憶,我再次把synchronized實(shí)現(xiàn)互斥的代碼貼上來(lái):
private synchronized void add10K(){
int start = 0;
while (start ++ < 10000){
this.count ++;
}
}
由于它倆都算互斥鎖,所以大家都喜歡拿它們做比較,我們來(lái)看看究竟有什么區(qū)別吧
ReentrantLock與synchronized的區(qū)別
1、重入
synchronized可重入,因?yàn)榧渔i和解鎖自動(dòng)進(jìn)行,不必?fù)?dān)心最后是否釋放鎖;ReentrantLock也可重入,但加鎖和解鎖需要手動(dòng)進(jìn)行,且次數(shù)需一樣,否則其他線程無(wú)法獲得鎖。
2、實(shí)現(xiàn)
synchronized是JVM實(shí)現(xiàn)的、而ReentrantLock是JDK實(shí)現(xiàn)的。說(shuō)白了就是,是操作系統(tǒng)來(lái)實(shí)現(xiàn),還是用戶自己敲代碼實(shí)現(xiàn)。
3、性能
在 Java 的 1.5 版本中,synchronized 性能不如 SDK 里面的 Lock,但 1.6 版本之后,synchronized 做了很多優(yōu)化,將性能追了上來(lái)。
4、功能
ReentrantLock鎖的細(xì)粒度和靈活度,都明顯優(yōu)于synchronized ,畢竟越麻煩使用的東西肯定功能越多啦!
特有功能一:可指定是公平鎖還是非公平鎖,而synchronized只能是非公平鎖。
公平的意思是先等待的線程先獲取鎖??梢栽跇?gòu)造函數(shù)中指定公平策略。
// 分別測(cè)試為true 和 為false的輸出。為true則輸出順序一定是A B C 但是為false的話有可能輸出A C B
private static final ReentrantLock reentrantLock = new ReentrantLock(true);
public static void main(String[] args) throws InterruptedException {
ReentrantLockDemo2 demo2 = new ReentrantLockDemo2();
Thread a = new Thread(() -> { test(); }, "A");
Thread b = new Thread(() -> { test(); }, "B");
Thread c = new Thread(() -> { test(); }, "C");
a.start();b.start();c.start();
}
public static void test() {
reentrantLock.lock();
try {
System.out.println("線程" + Thread.currentThread().getName());
} finally {
reentrantLock.unlock();//一定要釋放鎖
}
}
在原子性文章的最后,我們還賣了個(gè)關(guān)子,以轉(zhuǎn)賬為例,說(shuō)明synchronized會(huì)導(dǎo)致死鎖的問(wèn)題,即兩個(gè)線程你等我的鎖,我等你的鎖,兩方都阻塞,不會(huì)釋放!為了方便,我再次把代碼貼上來(lái):
static void transfer(Account source,Account target, int amt) throws InterruptedException {
// 鎖定轉(zhuǎn)出賬戶 Thread1鎖定了A Thread2鎖定了B
synchronized (source) {
Thread.sleep(1000);
log.info("持有鎖{} 等待鎖{}",source,target);
// 鎖定轉(zhuǎn)入賬戶 Thread1需要獲取到B,可是被Thread2鎖定了。Thread2需要獲取到A,可是被Thread1鎖定了。所以互相等待、死鎖
synchronized (target) {
if (source.getBalance() > amt) {
source.setBalance(source.getBalance() - amt);
target.setBalance(target.getBalance() + amt);
}
}
}
}
而ReentrantLock可以完美避免死鎖問(wèn)題,因?yàn)樗梢云茐乃梨i四大必要條件之一的:不可搶占條件。這得益于它這么幾個(gè)功能:
特有功能二:非阻塞地獲取鎖。如果嘗試獲取鎖失敗,并不進(jìn)入阻塞狀態(tài),而是直接返回false,這時(shí)候線程不用阻塞等待,可以先去做其他事情。所以不會(huì)造成死鎖。
// 支持非阻塞獲取鎖的 API
boolean tryLock();
現(xiàn)在我們用ReentrantLock來(lái)改造一下死鎖代碼
static void transfer(Account source, Account target, int amt) throws InterruptedException {
Boolean isContinue = true;
while (isContinue) {
if (source.getLock().tryLock()) {
log.info("{}已獲取鎖 time{}", source.getLock(),System.currentTimeMillis());
try {
if (target.getLock().tryLock()) {
log.info("{}已獲取鎖 time{}", target.getLock(),System.currentTimeMillis());
try {
log.info("開(kāi)始轉(zhuǎn)賬操作");
source.setBalance(source.getBalance() - amt);
target.setBalance(target.getBalance() + amt);
log.info("結(jié)束轉(zhuǎn)賬操作 source{} target{}", source.getBalance(), target.getBalance());
isContinue=false;
} finally {
log.info("{}釋放鎖 time{}", target.getLock(),System.currentTimeMillis());
target.getLock().unlock();
}
}
} finally {
log.info("{}釋放鎖 time{}", source.getLock(),System.currentTimeMillis());
source.getLock().unlock();
}
}
}
}
tryLock還支持超時(shí)。調(diào)用tryLock時(shí)沒(méi)有獲取到鎖,會(huì)等待一段時(shí)間,如果線程在一段時(shí)間之內(nèi)還是沒(méi)有獲取到鎖,不是進(jìn)入阻塞狀態(tài),而是throws InterruptedException,那這個(gè)線程也有機(jī)會(huì)釋放曾經(jīng)持有的鎖,這樣也能破壞死鎖不可搶占條件。
boolean tryLock(long time, TimeUnit unit)
特有功能三:提供能夠中斷等待鎖的線程的機(jī)制
synchronized 的問(wèn)題是,持有鎖 A 后,如果嘗試獲取鎖 B 失敗,那么線程就進(jìn)入阻塞狀態(tài),一旦發(fā)生死鎖,就沒(méi)有任何機(jī)會(huì)來(lái)喚醒阻塞的線程。
但如果阻塞狀態(tài)的線程能夠響應(yīng)中斷信號(hào),也就是說(shuō)當(dāng)我們給阻塞的線程發(fā)送中斷信號(hào)的時(shí)候,能夠喚醒它,那它就有機(jī)會(huì)釋放曾經(jīng)持有的鎖 A。這樣就破壞了不可搶占條件了。ReentrantLock可以用lockInterruptibly方法來(lái)實(shí)現(xiàn)。
public static void main(String[] args) throws InterruptedException {
ReentrantLockDemo5 demo2 = new ReentrantLockDemo5();
Thread th1 = new Thread(() -> {
try {
deadLock(reentrantLock1, reentrantLock2);
} catch (InterruptedException e) {
System.out.println("線程A被中斷");
}
}, "A");
Thread th2 = new Thread(() -> {
try {
deadLock(reentrantLock2, reentrantLock1);
} catch (InterruptedException e) {
System.out.println("線程B被中斷");
}
}, "B");
th1.start();
th2.start();
th1.interrupt();
}
public static void deadLock(Lock lock1, Lock lock2) throws InterruptedException {
lock1.lockInterruptibly(); //如果改成用lock那么是會(huì)一直死鎖的
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
lock2.lockInterruptibly();
try {
System.out.println("執(zhí)行完成");
} finally {
lock1.unlock();
lock2.unlock();
}
}
特有功能四、可以用J.U.C包中的Condition實(shí)現(xiàn)分組喚醒需要等待的線程。而synchronized只能notify或者notifyAll。這里涉及到線程之間的協(xié)作,在后續(xù)章節(jié)會(huì)詳細(xì)講解,敬請(qǐng)關(guān)注公眾號(hào)【胖滾豬學(xué)編程】。
文中代碼github地址:
本文轉(zhuǎn)載自公眾號(hào)【胖滾豬學(xué)編程】 用漫畫(huà)讓編程so easy and interesting!歡迎關(guān)注!