volidate 不保证原子性测试

51 阅读1分钟
public class Test {

    public static volatile int num = 0;
    public static void main(String[] args) {
        for (int i=0; i<100; i++) {
            new Thread(() -> {
                for (int j=0; j<1000; j++) {
                    num ++;
//                    synchronized(Test.class) {
//                        num ++;
//                    }
                }
            }).start();
        }
        try {
            Thread.sleep(1000);
            System.out.println(num);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}