自旋锁理论知识与代码验证
自旋锁
相对互斥锁,自旋锁是一种轻量级的锁,通过循环判断当前锁是否被其他线程获取,直到该线程获取到锁,才退出循环。自旋锁的优点是减少了线程上下文切换的消耗, 缺点是如果获取锁的线程一直处于活跃状态,则会占用大量的CPU资源消耗。
如JAVA中Atomic原子类就是用自旋锁的思想,以轻量级锁的方式实现原子性。
public final int getAndAddInt(Object var1, long var2, int var4) {
int var5;
do {
var5 = this.getIntVolatile(var1, var2);
} while(!this.compareAndSwapInt(var1, var2, var5, var5 + var4));
return var5;
}
自旋锁用JAVA代码进行验证
public class SpinLock {
AtomicReference<Thread> atomicReference = new AtomicReference<Thread>();
/**
* @author: dongchao
* @create: 2021/3/22-10:45
* @description: 进行加CAS自旋
* @param:
* @return:
*/
public void addLock(){
Thread thread = Thread.currentThread();
while (!atomicReference.compareAndSet(null,thread)){
//直到对比成功 ,即想到于获取到锁,开始执行业务操作
}
System.out.println(thread.getName()+"获取到锁!");
}
/**
* @author: dongchao
* @create: 2021/3/22-10:45
* @description: 解锁
* @param:
* @return:
*/
public void unLock(){
Thread thread = Thread.currentThread();
System.out.println(thread.getName()+"获取释放锁!");
atomicReference.compareAndSet(thread,null);
}
public static void main(String[] args) {
SpinLock spinLock = new SpinLock();
Thread thread1 = new Thread(() -> {
spinLock.addLock();
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
spinLock.unLock();
},"thread1");
thread1.start();
Thread thread2 = new Thread(() -> {
spinLock.addLock();
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
spinLock.unLock();
},"thread2");
thread2.start();
}
}
将Thread1线程Sleep 4s ,即4s后Thread1才会释放锁,即这样线程Thread2需要在While循环不断的判断compareAndSet 4秒后才能获取到锁。