示例:不通过 synchronized 和 lock ,就实现了锁的功能,自己实现自旋锁
public class Caslock {
//是否加锁,初始值为 false,也就是未加锁
private AtomicBoolean atomicBoolean =new AtomicBoolean(false);
public void lock(){
System.out.println(Thread.currentThread().getName()+",尝试加锁");
//原子布尔的值是否是false,是就加锁,把值改为true,不是就释放锁
while (!atomicBoolean.compareAndSet(false,true)){
//不是false,加锁失败,由其他线程先加了锁,这里就需要等待
try {
Thread.sleep(100);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
System.out.println(Thread.currentThread().getName()+",加锁成功");
}
public void unLock(){
//解锁,把值设为 false
atomicBoolean.compareAndSet(true,false);
System.out.println(Thread.currentThread().getName()+",释放锁");
}
}
private static void testCasLock() throws Exception{
Caslock caslock = new Caslock();
new Thread(()->{
caslock.lock();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
caslock.unLock();
},"线程A").start();
Thread.sleep(500);
new Thread(()->{
caslock.lock();
caslock.unLock();
},"线程B").start();
}
CAS的缺点
循环时间太长的话,开销会很大
ABA问题
想要解决ABA问题,需要加上版本号或者时间戳