CAS 包含了三个操作数:
①内存值 V
②预估值 A
③更新值 B
当且仅当 V == A 时, V = B; 否则,不会执行任何操作。
话题三:CAS效率比synchronized效率高吗?
CAS比synchronized效率高
多线程时,因为要compare,所以能够保证只有一个线程在操作数据
其他的线程不会被阻塞(可以手动写相关逻辑,再次操作数据,直至成功操作数据)
话题四:模拟CAS算法?
// 目标:有一个参考值,和参考值进行比较,相同就进行重新赋值
public class TestCompareAndSwap {
public static void main(String[] args) {
final CompareAndSwap cas = new CompareAndSwap();
for (int i = 0; i < 10; i++) {
new Thread(new Runnable() {
@Override
public void run() {
int expectedValue = cas.get();
boolean b = cas.compareAndSet(expectedValue, (int)(Math.random() * 101));
System.out.println(b);
}
}).start();
}
}
}
class CompareAndSwap {
private int value;
// 获得内存中的值
public synchronized int get() {
return value;
}
// 比较并且赋值
public synchronized int compareAndSwap(int exceptValue, int newValue) {
if (exceptValue == value) {
value = newValue;
}
return newValue;
}
// 判断是否成功赋值
public synchronized boolean compareAndSet(int exceptValue, int newValue) {
return value == compareAndSwap(exceptValue, newValue);
}
}