CAS
- CAS是原子类中提供的一种方法(compareAndSet),这个方法是硬件级别的实现,保证了这个方法的执行是原子性的,而例如i++,不是原子性的,它包含了取值等一系列微指令。
- 这个方法的作用是,当调用实例的值和expect相等时,就将实例的值设置为update
自旋锁
自旋锁基于CAS,线程1和线程2尝试共享区
- 如果1成功进入,就会将lock的值设置为false,
- 此时对于2来说,由于lock为false,会陷入到while的死循环中(自旋),直到1出来,将lock设置为true
AtomicBoolean lock = new AtomicBoolean(true);
void lock(){
while (!lock.compareAndSet(true,false)){
}
}
void unlock(){
lock.compareAndSet(false,true);
}
基于自旋锁的自增
public class t0 {
static AtomicInteger spin_I = new AtomicInteger(1);
public static void main(String[] args) throws InterruptedException {
Runnable runnable = () -> {
for (int i = 0; i < 1000; i++) {
System.out.println(getAndIncrement());
}
};
new Thread(runnable, "A").start();
new Thread(runnable, "B").start();
new Thread(runnable, "C").start();
}
static int getAndIncrement() {
int n;
do {
n = spin_I.get();
} while (!spin_I.compareAndSet(n, n + 1));
return n;
}
}