volatile-无原子性案例详解

package com.nanjing.gulimall.zhouyimo.controller;

import java.util.concurrent.TimeUnit;

/**
 * @author zhou
 * @version 1.0
 * @date 2023/11/5 7:56 下午
 */
class MyNumber{
    int number;
    public synchronized void add(){
        number++;
    }
}
public class VolatileNoAtomicDemo {
    public static void main(String[] args) {
        MyNumber myNumber = new MyNumber();
        //10个线程,每个线程操作1000次
        for (int i = 0; i < 10; i++) {
            new Thread(()->{
                for (int j = 0; j < 1000; j++) {
                    myNumber.add();
                }
            },String.valueOf(i)).start();
        }

        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println(myNumber.number);
    }
}


//10000

volatile-无原子性案例详解_第1张图片

 

 

你可能感兴趣的:(JUC并发编程与源码分析,java,算法,开发语言)