public class Sync01 implements Runnable {
static AtomicInteger i = new AtomicInteger();
public static void main(String[] args) throws InterruptedException {
Sync01 sync01 = new Sync01();
Sync01 sync02 = new Sync01();
Thread thread = new Thread(sync01);
Thread thread2 = new Thread(sync02);
thread.start();
thread2.start();
thread.join();
thread2.join();
System.out.println(i);
}
@Override
public void run() {
add();
}
private void add() {
synchronized (this) {
for (int j = 0; j < 10000; j++) {
i.incrementAndGet();
}
}
}
}
public class AtomicBooleanExample {
AtomicBoolean atomicBoolean = new AtomicBoolean(false);
public void shutDown() {
atomicBoolean.compareAndSet(false,true);
}
public void doWork() {
while (!atomicBoolean.get()) {
}
System.out.println("你能读到我们...");
}
public static void main(String[] args) throws InterruptedException {
AtomicBooleanExample volatile01 = new AtomicBooleanExample();
new Thread(() -> {
volatile01.doWork();
}).start();
Thread.sleep(2000);
new Thread(() -> {
volatile01.shutDown();
}).start();
}
}
ABA问题
public class AtomicIntegerABAExample {
private static AtomicInteger atomicInt = new AtomicInteger(100);
public static void main(String[] args) throws InterruptedException {
Thread intT1 = new Thread(new Runnable() {
@Override
public void run() {
atomicInt.compareAndSet(100, 101);
atomicInt.compareAndSet(101, 100);
}
});
Thread intT2 = new Thread(new Runnable() {
@Override
public void run() {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
boolean c3 = atomicInt.compareAndSet(100, 101);
System.out.println(c3);
}
});
intT1.start();
intT2.start();
intT1.join();
intT2.join();
}
}
输出true
解决 添加版本号
public class AtomicStampedReferenceABAExample {
private static AtomicStampedReference atomicStampedRef = new AtomicStampedReference(100, 0);
public static void main(String[] args) throws InterruptedException {
Thread intT1 = new Thread(new Runnable() {
@Override
public void run() {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
}
atomicStampedRef.compareAndSet(100, 101, atomicStampedRef.getStamp(), atomicStampedRef.getStamp() + 1);
atomicStampedRef.compareAndSet(101, 100, atomicStampedRef.getStamp(), atomicStampedRef.getStamp() + 1);
}
});
Thread intT2 = new Thread(new Runnable() {
@Override
public void run() {
int stamp = atomicStampedRef.getStamp();
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
}
boolean c3 = atomicStampedRef.compareAndSet(100, 101,stamp,stamp+1);
System.out.println(c3);
}
});
intT1.start();
intT2.start();
intT1.join();
intT2.join();
}
}
网友评论