volatile非原子性的示例

volatile非原子性的示例

package com.stono.thread2.page124;

public class MyThread extends Thread {

    volatile public static int count;
    private static void addCount() {
        for(int i=0;i<100;i++) {
            count++;
        }
        System.out.println("count = "+count);
    }
    
    @Override
    public void run() {
        addCount();
    }
}
package com.stono.thread2.page124;

public class Run {

    public static void main(String[] args) {
        MyThread [] myThreads = new MyThread[100];
        for(int i=0;i<100;i++) {
            myThreads[i] = new MyThread();
        }
        for(int i=0;i<100;i++) {
            myThreads[i].start();
        }
    }

}

对于count变量,存在非线程安全的问题,多个线程同时对count进行++操作,最后导致count的结果不是10000;

示例来源于《Java多线程编程核心技术》- 高洪岩著 Page 124