摘要
Lock在硬件層面依賴CPU指令,完全由Java代碼完成,底層利用LockSupport類和Unsafe類進(jìn)行操作;
雖然鎖有很多實(shí)現(xiàn),但是都依賴AbstractQueuedSynchronizer類,我們用ReentrantLock進(jìn)行講解;
ReentrantLock調(diào)用過程
ReentrantLock類的API調(diào)用都委托給一個(gè)內(nèi)部類 Sync ,而該類繼承了 AbstractQueuedSynchronizer類;
public class ReentrantLock implements Lock, java.io.Serializable { ...... abstract static class Sync extends AbstractQueuedSynchronizer { ......
而Sync又分為兩個(gè)子類:公平鎖和非公平鎖,默認(rèn)為非公平鎖
/** * Sync object for non-fair locks