update demo for ABA problem
This commit is contained in:
parent
9578efe639
commit
a7a720bc00
@ -41,6 +41,11 @@ public class CASByAtomicInteger {
|
||||
Thread t1 = new Thread(() -> {
|
||||
int initValue = unSafeCounter.get();
|
||||
System.out.println(STR."Thread 1: Initial value = \{initValue}");
|
||||
try {
|
||||
Thread.sleep(10);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
unSafeCounter.compareAndSet(0,20);
|
||||
unSafeCounter.compareAndSet(20,0);
|
||||
@ -51,13 +56,13 @@ public class CASByAtomicInteger {
|
||||
|
||||
Thread t2 = new Thread(() -> {
|
||||
int value = unSafeCounter.get();
|
||||
System.out.println("Thread 2: Initial value = " + value);
|
||||
try {
|
||||
// 等待线程1完成 ABA 操作
|
||||
Thread.sleep(100);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
System.out.println("Thread 2: Initial value = " + value);
|
||||
|
||||
// 尝试 CAS 操作
|
||||
boolean success = unSafeCounter.compareAndSet(0, 30); // A -> C
|
||||
|
Loading…
x
Reference in New Issue
Block a user