package com.autonavi.collapse.deteleable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicStampedReference;
import java.util.stream.IntStream;
public class Test {
//验证volatile的线程安全问题
private static class Test1 {
private volatile static Integer integer = 0;
public static void main(String[] args) throws InterruptedException {
CountDownLatch countDownLatch = new CountDownLatch(10);
IntStream.range(0,10).forEach(i -> {
countDownLatch.countDown();
new Thread(() -> {
IntStream.range(0,100).forEach(ii ->{
integer++;
});
}).start();
});
countDownLatch.await();
System.out.println(integer);
}
}
//AtomicInteger cas乐观锁的累加方式
private static class Test2 {
public static void main(String[] args) throws Exception {
AtomicInteger atomicInteger = new AtomicInteger(0);
CountDownLatch countDownLatch = new CountDownLatch(10);
IntStream.range(0,10).forEach(i -> {
new Thread(() -> {
IntStream.range(0,100).forEach(ii -> {
atomicInteger.getAndIncrement();
});
countDownLatch.countDown();
}).start();
});
countDownLatch.await();
System.out.println(atomicInteger);
}
}
//cas下的ABA问题复现
private static class Test3 {
public static void main(String[] args) throws Exception {
AtomicInteger atomicInteger = new AtomicInteger(100);
Thread thread = new Thread(() -> {
atomicInteger.compareAndSet(100,101);
atomicInteger.compareAndSet(101,100);
});
Thread thread1 = new Thread(() -> {
try {
Thread.sleep(1L);
} catch (InterruptedException e) {
e.printStackTrace();
}
boolean b = atomicInteger.compareAndSet(100,101);
if (b) {
System.out.println("验证成功");
} else {
System.out.println("验证失败");
}
});
thread.start();
thread1.start();
thread.join();
thread1.join();
System.out.println(atomicInteger);
}
}
//cas下的ABA问题复现
private static class Test4 {
public static void main(String[] args) throws Exception {
AtomicStampedReference atomicInteger = new AtomicStampedReference(100,1);
Thread thread = new Thread(() -> {
atomicInteger.compareAndSet(100,101,1,2);
atomicInteger.compareAndSet(101,100,2,3);
});
Thread thread1 = new Thread(() -> {
try {
Thread.sleep(1L);
} catch (InterruptedException e) {
e.printStackTrace();
}
boolean b = atomicInteger.compareAndSet(100,101,1,2);
if (b) {
System.out.println("验证成功");
} else {
System.out.println("验证失败");
}
});
thread.start();
thread1.start();
thread.join();
thread1.join();
System.out.println(atomicInteger.getReference());
}
}
}
AtomicInteger cas乐观锁的累加方式 & cas下的ABA问题复现
最新推荐文章于 2024-08-30 08:56:18 发布