Java同步锁——lock与synchronized 的区别【转】
在網(wǎng)上看來很多關(guān)于同步鎖的博文,記錄下來方便以后閱讀
?
一、Lock和synchronized有以下幾點(diǎn)不同:
1)Lock是一個(gè)接口,而synchronized是Java中的關(guān)鍵字,synchronized是內(nèi)置的語言實(shí)現(xiàn),synchronized是在JVM層面上實(shí)現(xiàn)的,不但可以通過一些監(jiān)控工具監(jiān)控synchronized的鎖定,而且在代碼執(zhí)行時(shí)出現(xiàn)異常,JVM會(huì)自動(dòng)釋放鎖定,但是使用Lock則不行,lock是通過代碼實(shí)現(xiàn)的,要保證鎖定一定會(huì)被釋放,就必須將 unLock()放到finally{} 中;
2)synchronized在發(fā)生異常時(shí),會(huì)自動(dòng)釋放線程占有的鎖,因此不會(huì)導(dǎo)致死鎖現(xiàn)象發(fā)生;而Lock在發(fā)生異常時(shí),如果沒有主動(dòng)通過unLock()去釋放鎖,則很可能造成死鎖現(xiàn)象,因此使用Lock時(shí)需要在finally塊中釋放鎖;
3)Lock可以讓等待鎖的線程響應(yīng)中斷,線程可以中斷去干別的事務(wù),而synchronized卻不行,使用synchronized時(shí),等待的線程會(huì)一直等待下去,不能夠響應(yīng)中斷;
4)通過Lock可以知道有沒有成功獲取鎖,而synchronized卻無法辦到。
5)Lock可以提高多個(gè)線程進(jìn)行讀操作的效率。
在性能上來說,如果競(jìng)爭(zhēng)資源不激烈,兩者的性能是差不多的,而當(dāng)競(jìng)爭(zhēng)資源非常激烈時(shí)(即有大量線程同時(shí)競(jìng)爭(zhēng)),此時(shí)Lock的性能要遠(yuǎn)遠(yuǎn)優(yōu)于synchronized。所以說,在具體使用時(shí)要根據(jù)適當(dāng)情況選擇。
?
舉個(gè)例子:當(dāng)有多個(gè)線程讀寫文件時(shí),讀操作和寫操作會(huì)發(fā)生沖突現(xiàn)象,寫操作和寫操作會(huì)發(fā)生沖突現(xiàn)象,但是讀操作和讀操作不會(huì)發(fā)生沖突現(xiàn)象。
但是采用synchronized關(guān)鍵字來實(shí)現(xiàn)同步的話,就會(huì)導(dǎo)致一個(gè)問題:
如果多個(gè)線程都只是進(jìn)行讀操作,所以當(dāng)一個(gè)線程在進(jìn)行讀操作時(shí),其他線程只能等待無法進(jìn)行讀操作。
因此就需要一種機(jī)制來使得多個(gè)線程都只是進(jìn)行讀操作時(shí),線程之間不會(huì)發(fā)生沖突,通過Lock就可以辦到。
另外,通過Lock可以知道線程有沒有成功獲取到鎖。這個(gè)是synchronized無法辦到的
?
?
?
二、ReentrantLock獲取鎖定與三種方式:
a) lock(), 如果獲取了鎖立即返回,如果別的線程持有鎖,當(dāng)前線程則一直處于休眠狀態(tài),直到獲取鎖
b) tryLock(), 如果獲取了鎖立即返回true,如果別的線程正持有鎖,立即返回false;
c)tryLock(long timeout,TimeUnit unit), 如果獲取了鎖定立即返回true,如果別的線程正持有鎖,會(huì)等待參數(shù)給定的時(shí)間,在等待的過程中,如果獲取了鎖定,就返回true,如果等待超時(shí),返回false;
d) lockInterruptibly:如果獲取了鎖定立即返回,如果沒有獲取鎖定,當(dāng)前線程處于休眠狀態(tài),直到或者鎖定,或者當(dāng)前線程被別的線程中斷
?
?
?
三、下面我們就來探討一下java.util.concurrent.locks包中常用的類和接口。
1.Lock
首先要說明的就是Lock,通過查看Lock的源碼可知,Lock是一個(gè)接口:
| 1 2 3 4 5 6 7 8 | public?interface?Lock { ????void?lock(); ????void?lockInterruptibly()?throws?InterruptedException; ????boolean?tryLock(); ????boolean?tryLock(long?time, TimeUnit unit)?throws?InterruptedException; ????void?unlock(); ????Condition newCondition(); } |
? 下面來逐個(gè)講述Lock接口中每個(gè)方法的使用,lock()、tryLock()、tryLock(long time, TimeUnit unit)和lockInterruptibly()是用來獲取鎖的。unLock()方法是用來釋放鎖的。newCondition()這個(gè)方法暫且不在此講述,會(huì)在后面的線程協(xié)作一文中講述。
在Lock中聲明了四個(gè)方法來獲取鎖,那么這四個(gè)方法有何區(qū)別呢?
首先lock()方法是平常使用得最多的一個(gè)方法,就是用來獲取鎖。如果鎖已被其他線程獲取,則進(jìn)行等待。
由于在前面講到如果采用Lock,必須主動(dòng)去釋放鎖,并且在發(fā)生異常時(shí),不會(huì)自動(dòng)釋放鎖。因此一般來說,使用Lock必須在try{}catch{}塊中進(jìn)行,并且將釋放鎖的操作放在finally塊中進(jìn)行,以保證鎖一定被被釋放,防止死鎖的發(fā)生。通常使用Lock來進(jìn)行同步的話,是以下面這種形式去使用的:
| 1 2 3 4 5 6 7 8 9 | Lock lock = ...; lock.lock(); try{ ????//處理任務(wù) }catch(Exception ex){ ????? }finally{ ????lock.unlock();???//釋放鎖 } |
tryLock()方法是有返回值的,它表示用來嘗試獲取鎖,如果獲取成功,則返回true,如果獲取失敗(即鎖已被其他線程獲取),則返回false,也就說這個(gè)方法無論如何都會(huì)立即返回。在拿不到鎖時(shí)不會(huì)一直在那等待。
tryLock(long time, TimeUnit unit)方法和tryLock()方法是類似的,只不過區(qū)別在于這個(gè)方法在拿不到鎖時(shí)會(huì)等待一定的時(shí)間,在時(shí)間期限之內(nèi)如果還拿不到鎖,就返回false。如果如果一開始拿到鎖或者在等待期間內(nèi)拿到了鎖,則返回true。
所以,一般情況下通過tryLock來獲取鎖時(shí)是這樣使用的:
| 1 2 3 4 5 6 7 8 9 10 11 12 | Lock lock = ...; if(lock.tryLock()) { ?????try{ ?????????//處理任務(wù) ?????}catch(Exception ex){ ????????? ?????}finally{ ?????????lock.unlock();???//釋放鎖 ?????}? }else?{ ????//如果不能獲取鎖,則直接做其他事情 } |
? lockInterruptibly()方法比較特殊,當(dāng)通過這個(gè)方法去獲取鎖時(shí),如果線程正在等待獲取鎖,則這個(gè)線程能夠響應(yīng)中斷,即中斷線程的等待狀態(tài)。也就使說,當(dāng)兩個(gè)線程同時(shí)通過lock.lockInterruptibly()想獲取某個(gè)鎖時(shí),假若此時(shí)線程A獲取到了鎖,而線程B只有在等待,那么對(duì)線程B調(diào)用threadB.interrupt()方法能夠中斷線程B的等待過程。
由于lockInterruptibly()的聲明中拋出了異常,所以lock.lockInterruptibly()必須放在try塊中或者在調(diào)用lockInterruptibly()的方法外聲明拋出InterruptedException。
因此lockInterruptibly()一般的使用形式如下:
| 1 2 3 4 5 6 7 8 9 | public?void?method()?throws?InterruptedException { ????lock.lockInterruptibly(); ????try?{?? ?????//..... ????} ????finally?{ ????????lock.unlock(); ????}?? } |
注意,當(dāng)一個(gè)線程獲取了鎖之后,是不會(huì)被interrupt()方法中斷的。因?yàn)楸旧碓谇懊娴奈恼轮兄v過單獨(dú)調(diào)用interrupt()方法不能中斷正在運(yùn)行過程中的線程,只能中斷阻塞過程中的線程。
因此當(dāng)通過lockInterruptibly()方法獲取某個(gè)鎖時(shí),如果不能獲取到,只有進(jìn)行等待的情況下,是可以響應(yīng)中斷的。
而用synchronized修飾的話,當(dāng)一個(gè)線程處于等待某個(gè)鎖的狀態(tài),是無法被中斷的,只有一直等待下去。
2.ReentrantLock
ReentrantLock,意思是“可重入鎖”,關(guān)于可重入鎖的概念在下一節(jié)講述。ReentrantLock是唯一實(shí)現(xiàn)了Lock接口的類,并且ReentrantLock提供了更多的方法。下面通過一些實(shí)例看具體看一下如何使用ReentrantLock。
例子1,lock()的正確使用方法
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | public?class?Test { ????private?ArrayList<Integer> arrayList =?new?ArrayList<Integer>(); ????public?static?void?main(String[] args)? { ????????final?Test test =?new?Test(); ????????? ????????new?Thread(){ ????????????public?void?run() { ????????????????test.insert(Thread.currentThread()); ????????????}; ????????}.start(); ????????? ????????new?Thread(){ ????????????public?void?run() { ????????????????test.insert(Thread.currentThread()); ????????????}; ????????}.start(); ????}?? ????? ????public?void?insert(Thread thread) { ????????Lock lock =?new?ReentrantLock();????//注意這個(gè)地方 ????????lock.lock(); ????????try?{ ????????????System.out.println(thread.getName()+"得到了鎖"); ????????????for(int?i=0;i<5;i++) { ????????????????arrayList.add(i); ????????????} ????????}?catch?(Exception e) { ????????????// TODO: handle exception ????????}finally?{ ????????????System.out.println(thread.getName()+"釋放了鎖"); ????????????lock.unlock(); ????????} ????} } |
? 各位朋友先想一下這段代碼的輸出結(jié)果是什么?
?View Code
也許有朋友會(huì)問,怎么會(huì)輸出這個(gè)結(jié)果?第二個(gè)線程怎么會(huì)在第一個(gè)線程釋放鎖之前得到了鎖?原因在于,在insert方法中的lock變量是局部變量,每個(gè)線程執(zhí)行該方法時(shí)都會(huì)保存一個(gè)副本,那么理所當(dāng)然每個(gè)線程執(zhí)行到lock.lock()處獲取的是不同的鎖,所以就不會(huì)發(fā)生沖突。
知道了原因改起來就比較容易了,只需要將lock聲明為類的屬性即可。
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | public?class?Test { ????private?ArrayList<Integer> arrayList =?new?ArrayList<Integer>(); ????private?Lock lock =?new?ReentrantLock();????//注意這個(gè)地方 ????public?static?void?main(String[] args)? { ????????final?Test test =?new?Test(); ????????? ????????new?Thread(){ ????????????public?void?run() { ????????????????test.insert(Thread.currentThread()); ????????????}; ????????}.start(); ????????? ????????new?Thread(){ ????????????public?void?run() { ????????????????test.insert(Thread.currentThread()); ????????????}; ????????}.start(); ????}?? ????? ????public?void?insert(Thread thread) { ????????lock.lock(); ????????try?{ ????????????System.out.println(thread.getName()+"得到了鎖"); ????????????for(int?i=0;i<5;i++) { ????????????????arrayList.add(i); ????????????} ????????}?catch?(Exception e) { ????????????// TODO: handle exception ????????}finally?{ ????????????System.out.println(thread.getName()+"釋放了鎖"); ????????????lock.unlock(); ????????} ????} } |
? 這樣就是正確地使用Lock的方法了。
例子2,tryLock()的使用方法
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | public?class?Test { ????private?ArrayList<Integer> arrayList =?new?ArrayList<Integer>(); ????private?Lock lock =?new?ReentrantLock();????//注意這個(gè)地方 ????public?static?void?main(String[] args)? { ????????final?Test test =?new?Test(); ????????? ????????new?Thread(){ ????????????public?void?run() { ????????????????test.insert(Thread.currentThread()); ????????????}; ????????}.start(); ????????? ????????new?Thread(){ ????????????public?void?run() { ????????????????test.insert(Thread.currentThread()); ????????????}; ????????}.start(); ????}?? ????? ????public?void?insert(Thread thread) { ????????if(lock.tryLock()) { ????????????try?{ ????????????????System.out.println(thread.getName()+"得到了鎖"); ????????????????for(int?i=0;i<5;i++) { ????????????????????arrayList.add(i); ????????????????} ????????????}?catch?(Exception e) { ????????????????// TODO: handle exception ????????????}finally?{ ????????????????System.out.println(thread.getName()+"釋放了鎖"); ????????????????lock.unlock(); ????????????} ????????}?else?{ ????????????System.out.println(thread.getName()+"獲取鎖失敗"); ????????} ????} } |
? 輸出結(jié)果:
?View Code
例子3,lockInterruptibly()響應(yīng)中斷的使用方法:
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | public?class?Test { ????private?Lock lock =?new?ReentrantLock();??? ????public?static?void?main(String[] args)? { ????????Test test =?new?Test(); ????????MyThread thread1 =?new?MyThread(test); ????????MyThread thread2 =?new?MyThread(test); ????????thread1.start(); ????????thread2.start(); ????????? ????????try?{ ????????????Thread.sleep(2000); ????????}?catch?(InterruptedException e) { ????????????e.printStackTrace(); ????????} ????????thread2.interrupt(); ????}?? ????? ????public?void?insert(Thread thread)?throws?InterruptedException{ ????????lock.lockInterruptibly();???//注意,如果需要正確中斷等待鎖的線程,必須將獲取鎖放在外面,然后將InterruptedException拋出 ????????try?{?? ????????????System.out.println(thread.getName()+"得到了鎖"); ????????????long?startTime = System.currentTimeMillis(); ????????????for(??? ;???? ;) { ????????????????if(System.currentTimeMillis() - startTime >= Integer.MAX_VALUE) ????????????????????break; ????????????????//插入數(shù)據(jù) ????????????} ????????} ????????finally?{ ????????????System.out.println(Thread.currentThread().getName()+"執(zhí)行finally"); ????????????lock.unlock(); ????????????System.out.println(thread.getName()+"釋放了鎖"); ????????}?? ????} } ? class?MyThread?extends?Thread { ????private?Test test =?null; ????public?MyThread(Test test) { ????????this.test = test; ????} ????@Override ????public?void?run() { ????????? ????????try?{ ????????????test.insert(Thread.currentThread()); ????????}?catch?(InterruptedException e) { ????????????System.out.println(Thread.currentThread().getName()+"被中斷"); ????????} ????} } |
運(yùn)行之后,發(fā)現(xiàn)thread2能夠被正確中斷。
3.ReadWriteLock
ReadWriteLock也是一個(gè)接口,在它里面只定義了兩個(gè)方法:
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | public?interface?ReadWriteLock { ????/** ?????* Returns the lock used for reading. ?????* ?????* @return the lock used for reading. ?????*/ ????Lock readLock(); ? ????/** ?????* Returns the lock used for writing. ?????* ?????* @return the lock used for writing. ?????*/ ????Lock writeLock(); } |
? 一個(gè)用來獲取讀鎖,一個(gè)用來獲取寫鎖。也就是說將文件的讀寫操作分開,分成2個(gè)鎖來分配給線程,從而使得多個(gè)線程可以同時(shí)進(jìn)行讀操作。下面的ReentrantReadWriteLock實(shí)現(xiàn)了ReadWriteLock接口。
4.ReentrantReadWriteLock
ReentrantReadWriteLock里面提供了很多豐富的方法,不過最主要的有兩個(gè)方法:readLock()和writeLock()用來獲取讀鎖和寫鎖。
下面通過幾個(gè)例子來看一下ReentrantReadWriteLock具體用法。
假如有多個(gè)線程要同時(shí)進(jìn)行讀操作的話,先看一下synchronized達(dá)到的效果:
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | public?class?Test { ????private?ReentrantReadWriteLock rwl =?new?ReentrantReadWriteLock(); ????? ????public?static?void?main(String[] args)? { ????????final?Test test =?new?Test(); ????????? ????????new?Thread(){ ????????????public?void?run() { ????????????????test.get(Thread.currentThread()); ????????????}; ????????}.start(); ????????? ????????new?Thread(){ ????????????public?void?run() { ????????????????test.get(Thread.currentThread()); ????????????}; ????????}.start(); ????????? ????}?? ????? ????public?synchronized?void?get(Thread thread) { ????????long?start = System.currentTimeMillis(); ????????while(System.currentTimeMillis() - start <=?1) { ????????????System.out.println(thread.getName()+"正在進(jìn)行讀操作"); ????????} ????????System.out.println(thread.getName()+"讀操作完畢"); ????} } |
? 這段程序的輸出結(jié)果會(huì)是,直到thread1執(zhí)行完讀操作之后,才會(huì)打印thread2執(zhí)行讀操作的信息。
?View Code
而改成用讀寫鎖的話:
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | public?class?Test { ????private?ReentrantReadWriteLock rwl =?new?ReentrantReadWriteLock(); ????? ????public?static?void?main(String[] args)? { ????????final?Test test =?new?Test(); ????????? ????????new?Thread(){ ????????????public?void?run() { ????????????????test.get(Thread.currentThread()); ????????????}; ????????}.start(); ????????? ????????new?Thread(){ ????????????public?void?run() { ????????????????test.get(Thread.currentThread()); ????????????}; ????????}.start(); ????????? ????}?? ????? ????public?void?get(Thread thread) { ????????rwl.readLock().lock(); ????????try?{ ????????????long?start = System.currentTimeMillis(); ????????????? ????????????while(System.currentTimeMillis() - start <=?1) { ????????????????System.out.println(thread.getName()+"正在進(jìn)行讀操作"); ????????????} ????????????System.out.println(thread.getName()+"讀操作完畢"); ????????}?finally?{ ????????????rwl.readLock().unlock(); ????????} ????} } |
? 此時(shí)打印的結(jié)果為:
?View Code
說明thread1和thread2在同時(shí)進(jìn)行讀操作。
這樣就大大提升了讀操作的效率。
不過要注意的是,如果有一個(gè)線程已經(jīng)占用了讀鎖,則此時(shí)其他線程如果要申請(qǐng)寫鎖,則申請(qǐng)寫鎖的線程會(huì)一直等待釋放讀鎖。
如果有一個(gè)線程已經(jīng)占用了寫鎖,則此時(shí)其他線程如果申請(qǐng)寫鎖或者讀鎖,則申請(qǐng)的線程會(huì)一直等待釋放寫鎖。
關(guān)于ReentrantReadWriteLock類中的其他方法感興趣的朋友可以自行查閱API文檔。
?
總結(jié)
以上是生活随笔為你收集整理的Java同步锁——lock与synchronized 的区别【转】的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 油价最新动向,国内成品油调价窗口两天后开
- 下一篇: java美元兑换,(Java实现) 美元