使用AtomicInteger原子类代替i++线程安全操作

Java中自增自减操作不具原子性,在多线程环境下是线程不安全的,可以使用使用AtomicInteger原子类代替i++,i--操作完成多线程线程安全操作。

下面是等于i++多线程的自增操作代码:

public class AtomicIntegerTest {
    private static AtomicInteger count = new AtomicInteger(0);

    public static void add() {
        for (int i = 0; i < 10000; i++) {
            System.out.println(count.incrementAndGet());
        }
    }

    public static void main(String[] args) {
        for (int i = 0; i < 8; i++) {
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    AtomicIntegerTest.add();
                }
            });
            thread.start();
        }
    }
}

 incrementAndGet()方法源码(JDK1.8):

    /**
     * Atomically increments by one the current value.
     *
     * @return the updated value
     */
    public final int incrementAndGet() {
        return unsafe.getAndAddInt(this, valueOffset, 1) + 1;
    }

  

猜你喜欢

转载自www.cnblogs.com/tangquanbin/p/10111449.html