AtomicInteger可以保证原子性,可见性,有序性
public class AtomicIntegerTest { private static AtomicInteger value = new AtomicInteger(); public static void main(String[] args) throws InterruptedException { Thread t1 = new Thread(new LoopVolatile()); t1.start(); Thread t2 = new Thread(new LoopVolatile2()); t2.start(); t1.join(); t2.join(); System.out.println("final val is: " + value); //20000 } private static class LoopVolatile implements Runnable { public void run() { long val = 0; while (val < 10000L) { value.getAndIncrement(); val++; } } } private static class LoopVolatile2 implements Runnable { public void run() { long val = 0; while (val < 10000L) { value.getAndIncrement(); val++; } } } }
getAndIncrement方法是线程安全的,是由Unsafe类来保证线程安全的。
public final int getAndIncrement() {
return unsafe.getAndAddInt(this, valueOffset, 1);
}