AtomicInteger类:
高并发的情况下,i++
无法保证原子性,往往会出现问题,所以引入AtomicInteger
类。并发编程中的原子性问题
AtomicInteger类工具方法:
private static AtomicInteger atomicInteger = new AtomicInteger();
// 获取当前值
public static void getCurrentValue(){}
// 设置value值
public static void setValue(){}
// 先获取旧值,然后设置新值
public static void getAndSet(){}
// 先获取旧值,然后再自增
public static void getAndIncrement(){}
// 先获取旧值,然后再自减
public static void getAndDecrement(){}
// 先获取旧值,然后再加
public static void getAndAdd(){}
// 先加1,然后获取新值
public static void incrementAndGet(){}
// 先减1,然后获取新值
public static void decrementAndGet(){}
// 先增加,然后获取值
public static void addAndGet(){}
顺序打印的使用:
class Foo {
private AtomicInteger firstJobDone = new AtomicInteger(0);
private AtomicInteger secondJobDone = new AtomicInteger(0);
public Foo() {}
public void first(Runnable printFirst) throws InterruptedException {
// printFirst.run() outputs "first".
printFirst.run();
// mark the first job as done, by increasing its count.
firstJobDone.incrementAndGet();
}
public void second(Runnable printSecond) throws InterruptedException {
while (firstJobDone.get() != 1) {
// waiting for the first job to be done.
}
// printSecond.run() outputs "second".
printSecond.run();
// mark the second as done, by increasing its count.
secondJobDone.incrementAndGet();
}
public void third(Runnable printThird) throws InterruptedException {
while (secondJobDone.get() != 1) {
// waiting for the second job to be done.
}
// printThird.run() outputs "third".
printThird.run();
}
}