天下脸皮共十分
我占八分

i++操作的非原子性

public class ItemFeatureDemo {

    static int i = 0;

    public static void main(String[] args) throws InterruptedException {
        Thread thread1 = new Thread(() -> {
            for (int j = 0; j < 50000; j++) {
                i++;
            }
        });
        Thread thread2 = new Thread(() -> {
            for (int j = 0; j < 50000; j++) {
                i--;
            }
        });
        thread1.start();
        thread2.start();
        thread1.join();
        thread2.join();
        System.out.println("i = " + i);
    }
}

// 假设i的初始值为0

getstatic i // 线程1-获取静态变量i的值 线程内i=0

getstatic i // 线程2-获取静态变量i的值 线程内i=0

iconst_1 // 线程1-准备常量1

iadd // 线程1-自增 线程内i=1

putstatic i // 线程1-将修改后的值存入静态变量i 静态变量i=1

iconst_1 // 线程2-准备常量1

isub // 线程2-自减 线程内i=-1

putstatic i // 线程2-将修改后的值存入静态变量i 静态变量i=-1

赞(0) 打赏
未经允许不得转载:Stephen Young » i++操作的非原子性
分享到: 更多 (0)

评论 抢沙发

评论前必须登录!

 

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏