什么是自旋鎖
當(dāng)cpu正在訪問獲取到自選鎖的臨界區(qū)费尽,讓其他也需要訪問該臨界區(qū)的,但并未獲得鎖的線程忙等待,而不是像可重入鎖一樣阻塞脸甘,所以自選鎖是一種針對多cpu的非阻塞鎖
public class SpinLock {
private AtomicReference<Thread> sign =new AtomicReference<>();
public void lock(){
Thread current = Thread.currentThread();
while(!sign .compareAndSet(null, current)){
}
}
public void unlock (){
Thread current = Thread.currentThread();
sign .compareAndSet(current, null);
}
}
自旋鎖
public class SpinLock {
private AtomicReference<Thread> owner =new AtomicReference<>();
public void lock(){
Thread current = Thread.currentThread();
while(!owner.compareAndSet(null, current)){
}
}
public void unlock (){
Thread current = Thread.currentThread();
owner.compareAndSet(current, null);
}
}
AtomicReference
Java多線程系列--“JUC原子類”04之 AtomicReference原子類
自旋鎖死鎖
如果鎖占有的代碼,和占有cpu的代碼(需要訪問臨界區(qū)獲取自旋鎖)在同一個處理機(jī)上祈争,則會產(chǎn)生死鎖斤程,占有鎖因?yàn)榈貌坏綍r(shí)間片,始終釋放不了鎖。
可重入鎖
鎖作為并發(fā)共享數(shù)據(jù)忿墅,保證一致性的工具扁藕,在JAVA平臺有多種實(shí)現(xiàn)(如 synchronized 和 ReentrantLock等等 ) 。
可重入鎖疚脐,也叫做遞歸鎖亿柑,指的是同一線程 外層函數(shù)獲得鎖之后 ,內(nèi)層遞歸函數(shù)仍然有獲取該鎖的代碼棍弄,但不受影響望薄。
自旋鎖和可重入鎖
如果搶占鎖的時(shí)間比較短暫,cpu會切換線程上下文呼畸,消耗性能痕支,這時(shí)自旋鎖就比較合適了,不會釋放cpu蛮原,忙等待直到其他線程改變卧须。