阿里面試實戰題2----ReentrantLock里面lock和tryLock的區別


ReentrantLock

ReentrantLock(輕量級鎖)也可以叫對象鎖,可重入鎖,互斥鎖。synchronized重量級鎖,JDK前期的版本lock比synchronized更快,在JDK1.5之后synchronized引入了偏向鎖,輕量級鎖和重量級鎖。以致兩種鎖性能旗鼓相當,看個人喜歡,本文主要介紹一下lock和tryLock的區別。

 

Lock VS  TryLock

 1 public void lock() {
 2     sync.lock();
 3 }
 4 
 5 public void lockInterruptibly() throws InterruptedException {
 6   sync.acquireInterruptibly(1);
 7 }
 8 
 9 
10 
11 public boolean tryLock() {
12     return sync.nonfairTryAcquire(1);
13 }
14 
15 
16 public boolean tryLock(long timeout, TimeUnit unit)
17         throws InterruptedException {
18     return sync.tryAcquireNanos(1, unit.toNanos(timeout));
19 }

 

舉一個例子如下:

 

假如線程A和線程B使用同一個鎖LOCK,此時線程A首先獲取到鎖LOCK.lock(),並且始終持有不釋放。如果此時B要去獲取鎖,有四種方式:

  • LOCK.lock(): 此方式會始終處於等待中,即使調用B.interrupt()也不能中斷,除非線程A調用LOCK.unlock()釋放鎖。

  • LOCK.lockInterruptibly(): 此方式會等待,但當調用B.interrupt()會被中斷等待,並拋出InterruptedException異常,否則會與lock()一樣始終處於等待中,直到線程A釋放鎖。

  • LOCK.tryLock(): 該處不會等待,獲取不到鎖並直接返回false,去執行下面的邏輯。

  • LOCK.tryLock(10, TimeUnit.SECONDS):該處會在10秒時間內處於等待中,但當調用B.interrupt()會被中斷等待,並拋出InterruptedException。10秒時間內如果線程A釋放鎖,會獲取到鎖並返回true,否則10秒過后會獲取不到鎖並返回false,去執行下面的邏輯。

 

Lock和TryLock的區別

1:  lock拿不到鎖會一直等待。tryLock是去嘗試,拿不到就返回false,拿到返回true。

2:  tryLock是可以被打斷的,被中斷 的,lock是不可以。

 

 

參考資料如下:https://www.zhihu.com/question/36771163/answer/68974735


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM