volatile

作用

  可见性

  内存屏障(指令重排的屏障)

    注意:不保证原子性

package com.draymond.three.actomic;

import org.junit.Test;

import java.io.IOException;

/**
 * AtomicInterger 测试
 *
 * @Auther: ZhangSuchao
 * @Date: 2020/3/20 10:27
 */
public class AtomicIntergerTest {
    private static volatile Integer value = 0; // volatile 可见性,内存屏障(不保证原子性)

    /**
     * volatile 测试
     *
     * @throws IOException
     */
    @Test
    public void test1() throws IOException {

        Thread thread1 = new Thread(() -> {
            while (true) {
                System.out.println(value++);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        Thread thread2 = new Thread(() -> {
            while (true) {
                System.out.println(value++);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        thread1.start();
        thread2.start();
        System.in.read();
    }
}

打印的结果有重复的

说明++操作不保证原子性,如果必须要共享,则需要加上synchorized

原文地址:https://www.cnblogs.com/draymond/p/12530269.html