4 回答

TA貢獻(xiàn)1772條經(jīng)驗(yàn) 獲得超6個(gè)贊
這個(gè)最好把Lock
的四個(gè)鎖法都比較一下(容我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.
在等待獲取鎖的過程中休眠并禁止一切線程調(diào)度
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.
在指定時(shí)間內(nèi)等待獲取鎖;過程中可被中斷
假如線程A
和線程B
使用同一個(gè)鎖LOCK
,此時(shí)線程A首先獲取到鎖LOCK.lock()
,并且始終持有不釋放。如果此時(shí)B要去獲取鎖,有四種方式:
LOCK.lock()
: 此方式會(huì)始終處于等待中,即使調(diào)用B.interrupt()
也不能中斷,除非線程A調(diào)用LOCK.unlock()
釋放鎖。LOCK.lockInterruptibly()
: 此方式會(huì)等待,但當(dāng)調(diào)用B.interrupt()
會(huì)被中斷等待,并拋出InterruptedException
異常,否則會(huì)與lock()
一樣始終處于等待中,直到線程A釋放鎖。LOCK.tryLock()
: 該處不會(huì)等待,獲取不到鎖并直接返回false,去執(zhí)行下面的邏輯。LOCK.tryLock(10, TimeUnit.SECONDS)
:該處會(huì)在10秒時(shí)間內(nèi)處于等待中,但當(dāng)調(diào)用B.interrupt()
會(huì)被中斷等待,并拋出InterruptedException
。10秒時(shí)間內(nèi)如果線程A釋放鎖,會(huì)獲取到鎖并返回true,否則10秒過后會(huì)獲取不到鎖并返回false,去執(zhí)行下面的邏輯。
是否會(huì)造成 程序不可控, 不在于這幾種方式本身,在于業(yè)務(wù)類別和使用邏輯上。

TA貢獻(xiàn)1802條經(jīng)驗(yàn) 獲得超5個(gè)贊

TA貢獻(xiàn)1801條經(jīng)驗(yàn) 獲得超16個(gè)贊
添加回答
舉報(bào)