/**
*compareAndSet是原子操作。内部是unsafe实现的
*atomicInteger的作用就是用来做乐观锁的
*/
private final AtomicInteger atomicInteger = new AtomicInteger(0);
private Integer num = 0;
@Test
public void test3() {
//打印奇数
new Thread(() -> {
while (true) {
while (atomicInteger.compareAndSet(0, 1)) {
num++;
System.out.println(num);
atomicInteger.compareAndSet(1,2);
if (num == 99) return;
}
}
}).start();
//打印偶数
new Thread(() -> {
while (true) {
while (atomicInteger.compareAndSet(2, 3)) {
num++;
System.out.println(num);
atomicInteger.compareAndSet(3,0);
if (num == 100) return;
}
}
}).start();
}
网友评论