Java多线程i++线程安全问题,volatile和AtomicInteger解释?
巴扎黑
巴扎黑 2017-04-18 09:53:42
0
5
788

在Java多线程中,i++和i--是非线程安全的。
例子:

public class PlusPlusTest {

    public static void main(String[] args) throws InterruptedException {
        Num num = new Num();
        ThreadA threadA = new ThreadA(num);
        ThreadB threadB = new ThreadB(num);
        threadA.start();
        threadB.start();
        Thread.sleep(200);
        System.out.println(num.count);
    }
}

class ThreadA extends Thread {
    private Num num;

    public ThreadA(Num num) {
        this.num = num;
    }

    @Override
    public void run() {
        for (int i = 0; i < 1000; i++) {
            num.count++;
        }
    }
}

class ThreadB extends Thread {
    private Num num;

    public ThreadB(Num num) {
        this.num = num;
    }

    @Override
    public void run() {
        for (int i = 0; i < 1000; i++) {
            num.count++;
        }
    }
}

class Num {
    int count = 0;

    public Num() {
    }
}

以上代码输出结果基本上不是2000,会比2000小。

原因:

在线程A中,i++的过程为:
temp1 = i; temp2 = temp1 + 1; i = temp2;
在线程B中,i++的过程为:
temp3 = i; temp4 = temp3 + 1; i = temp4;

在i=0的时候,线程A和B同时读取i=0。
线程A执行++后,i被修改成1。
线程B执行++后,i被修改,但还是1。

问:这样的解释对么?


想到把count变量申明为volatile,但是:

即使把count申明为volatile,输出的结果也不是2000,请问为什么?

class Num {
    volatile int count = 0;

    public Num() {
    }
}


最后

把count变量包装成AtomicInteger之后,输出的结果为2000,正确,这又是为什么?

巴扎黑
巴扎黑

全部回覆(5)
大家讲道理

问:这样的解释对么?

其实不是很妥当,i++的操作应该没有那么麻烦,读值是指读到CPU
出现错误,执行顺序如下:

  1. 线程1读到i的值为0

  2. 线程2也读到i的值为0

  3. 线程1执行了+1操作,将结果值1写入到内存,

  4. 线程2执行了+1操作,将结果值1写入到内存。

即使把count申明为volatile,输出的结果也不是2000,请问为什么?

volatile只能保证可见性,就是说实时读到i的最新值,但不能保证原子性,即上述执行顺序完全允许出现。这个还可以参考我关于这个问题的回答:https://segmentfault.com/q/10...

把count变量包装成AtomicInteger之后,输出的结果为2000,正确,这又是为什么?

AtomicInteger是原子的int,这个是由Java实现的,大概理解下源码:

 /**
     * Atomically increments by one the current value.
     *
     * @return the previous value
     */
    public final int getAndIncrement() {
        for (;;) {
            int current = get();
            int next = current + 1;
            if (compareAndSet(current, next))
                return current;
        }
    }
    
    public final boolean compareAndSet(int expect, int update) {
        return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
    }

重点是compareAndSet(),这个方法会判断currenti的值是否满足条件:此时i的值是否和current相等,满足条件了直接退出循环,不然再++一遍,直到正常。
compareAndSet方法是由Java的unsafe实现的,这个应该很底层了,都是native方法,我也没研究过。不过,一般程序员是不会接触到unsafe编程的。

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!