4 回答

TA貢獻1772條經驗 獲得超6個贊
這個最好把Lock
的四個鎖法都比較一下(容我copy些東西):
void lock();
If the lock is not available then the current thread becomes disabled for thread scheduling purposes and lies dormant until the lock has been acquired.
在等待獲取鎖的過程中休眠并禁止一切線程調度
void lockInterruptibly() throws InterruptedException;
If the lock is not available then the current thread becomes disabled for thread scheduling purposes and lies dormant until one of two things happens:
The lock is acquired by the current thread; or Some other thread interrupts the current thread, and interruption of lock acquisition is supported.
在等待獲取鎖的過程中可被中斷
boolean tryLock();
Acquires the lock if it is available and returns immediately with the value true. If the lock is not available then this method will return immediately with the value false.
獲取到鎖并返回true;獲取不到并返回false
*boolean tryLock(long time, TimeUnit unit) throws InterruptedException;
If the lock is available this method returns immediately with the value true. If the lock is not available then the current thread becomes disabled for thread scheduling purposes and lies dormant until one of three things happens:The lock is acquired by the current thread; or Some other thread interrupts the current thread, and interruption of lock acquisition is supported; or The specified waiting time elapses.
在指定時間內等待獲取鎖;過程中可被中斷
假如線程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,去執行下面的邏輯。
是否會造成 程序不可控, 不在于這幾種方式本身,在于業務類別和使用邏輯上。

TA貢獻1802條經驗 獲得超5個贊

TA貢獻1801條經驗 獲得超16個贊
添加回答
舉報