自旋锁就是获取锁的线程不会立即阻塞,用循环的方式尝试获取锁,好处就是减少了线程上下文切换的消耗,缺点就是循环消耗cpu,java.util.concurrent.atomic 下的AtomicInteger 就是靠CAS 自旋实现的。
package com.example.mycloud.mycloud.util;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
public class CasTest {
AtomicReference<Thread> atomicReference=new AtomicReference<>();
void mylock(){
Thread thread=Thread.currentThread();
//加锁 当前atomicReference 为空 上锁
while (!atomicReference.compareAndSet(null,thread)){
// System.out.println("自旋"+Thread.currentThread().getName());// 自旋尝试获取锁
}
System.out.println("加锁"+Thread.currentThread().getName());
}
void myunlock(){
Thread thread=Thread.currentThread();
atomicReference.compareAndSet(thread,null);
System.out.println("释放"+Thread.currentThread().getName());
}
public static void main(String[] args) throws InterruptedException {
CasTest casTest=new CasTest();
new Thread(()->{
casTest.mylock();
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
casTest.myunlock();
},"线程1").start();
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread(()->{
casTest.mylock();
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
casTest.myunlock();
},"线程2").start();
}
}
执行结果为:
加锁线程1
释放线程1
加锁线程2
释放线程2