Lock接口:
public interface Lock {
void lock();
void lockInterruptibly() throws InterruptedException;
boolean tryLock();
boolean tryLock(long time, TimeUnit unit) throws InterruptedException;
void unlock();
Condition newCondition();
}
Lock接口是鎖操作的基礎(chǔ),后面的所有的鎖實(shí)現(xiàn)都會(huì)實(shí)現(xiàn)Lock接口聊训。
- 最無賴的做法:lock(), 拿不到鎖就等著抱究,知道拿到位置恢氯。
- 最瀟灑的做法:tryLock():boolean, 拿不到鎖就返回false带斑,拿到鎖就返回true鼓寺,并持有鎖。
- 最聰明的做法:tryLock(long time, TimeUnit unit) :boolean, 拿不到鎖就等一會(huì)勋磕,如果還拿不到就返回false妈候,如果拿到了鎖就返回true,并持有鎖挂滓。
- 最無賴而且危險(xiǎn)的做法:lockInterruptibly(), 在普通lock()時(shí)苦银,如果線程被interrupt,其實(shí)現(xiàn)成是不理會(huì)的赶站,只是通過isInterrupted可以判斷外界是否interrupt了幔虏。但是在lockInterruptibly中就不是這樣的,如果外界interrupt了贝椿,則這個(gè)線程就會(huì)立刻處理想括,并拋出異常InterruptedException。這一點(diǎn)跟sleep,wait,join很像烙博。
ReentrantLock
ReentrantLock的定義是這樣的: ReentrantLock implements Lock, java.io.Serializable瑟蜈。 它實(shí)現(xiàn)了Lock接口,是Lock最常用的類渣窜。