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