volatile引发的一个有趣的测试

转载请以链接形式标明出处:
本文出自:103style的博客

本文是 看到 这篇文章中 “volatile 的意义?” 那一小节提供的一个例子引发的测试。

volatile 的意义?

  • 防止CPU指令重排序

volatile有两条关键的语义:

  • 保证被volatile修饰的变量对所有线程都是可见的
  • 禁止进行指令重排序

volatile变量具有下列特性:

  • 可见性:总是能看到(任意线程)对这个volatile变量最后的写入。
  • 原子性:对任意单个volatile变量的读/写具有原子性,但类似于volatile++这种复合操作不具有原子性。

下面的例子是用来证明下面这个观点的后半句是错误的。

由于volatile修饰的变量在各个线程里都是一致的,所以基于volatile变量的运算在多线程并发的情况下是安全的。


原测试示例

例子是这样的:

public class Test {
    private volatile int start = 0;
    public static void main(String[] args) {
        new Test().test();
    }
    private void test() {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                add();
            }
        };
        for (int i = 0; i < 10; i++) {
            Thread thread = new Thread(runnable);
            thread.start();
        }
        System.out.println("start = " + start);
    }
    void add() {
        for (int i = 0; i < 10; i++) {
            start++;
        }
    }
}

大家可以看看 最后运行的结果输出的 start 值是多少 ?


给 add 方法加上 synchronized 之后

add() 方法加上 synchronized 之后输出的 start 值又是多少呢 ?

public class Test {
    private volatile int start = 0;
    public static void main(String[] args) {
        new Test().test();
    }
    private void test() {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                add();
            }
        };
        for (int i = 0; i < 10; i++) {
            Thread thread = new Thread(runnable);
            thread.start();
        }
        System.out.println("start = " + start);
    }
    synchronized void add() {
        for (int i = 0; i < 10; i++) {
            start++;
        }
    }
}

两个测试的结果

两个结果都是 100? 还是只有第二个是100 ?

其实两个结果都不是100,这是因为 main方法对应的线程 不会等待 新创建的线程执行完。

我们可以加上时间输出看看试试:

public class Test {
    private volatile int start = 0;
    public static void main(String[] args) {
        new Test().test();
    }
    private void test() {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                add();
                System.out.println("new thread: " + System.currentTimeMillis());
            }
        };
        for (int i = 0; i < 10; i++) {
            Thread thread = new Thread(runnable);
            thread.start();
        }
        System.out.println("start = " + start);
        System.out.println("main: " + System.currentTimeMillis());
    }
    void add() {
        for (int i = 0; i < 10; i++) {
            start++;
        }
    }
}

控制台打印的结果:

new thread: 1583915204005
new thread: 1583915204005
new thread: 1583915204007
new thread: 1583915204007
new thread: 1583915204007
new thread: 1583915204007
start = 60
main: 1583915204007
new thread: 1583915204008
new thread: 1583915204008
new thread: 1583915204008
new thread: 1583915204008

可以看到 main方法对应的线程 先执行完了。

然后为了解决 main方法对应的线程 先执行完, 我们加上 Thread.sleep(1000); 看看:

public class Test {
    private volatile int start = 0;
    public static void main(String[] args) {
        new Test().test();
    }
    private void test() {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                add();
                System.out.println("new thread: " + System.currentTimeMillis());
            }
        };
        for (int i = 0; i < 10; i++) {
            Thread thread = new Thread(runnable);
            thread.start();
        }
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("start = " + start);
        System.out.println("main: " + System.currentTimeMillis());
    }
    void add() {
        for (int i = 0; i < 10; i++) {
            start++;
        }
    }
}

查看控制台输出:

new thread: 1583915390819
new thread: 1583915390821
new thread: 1583915390822
new thread: 1583915390823
new thread: 1583915390823
new thread: 1583915390823
new thread: 1583915390823
new thread: 1583915390823
new thread: 1583915390823
new thread: 1583915390823
start = 100
main: 1583915391822

去掉修饰 start 的 volatile 修饰符

然后我们试试把 volatile 修饰符 去掉试试,运行的结果输出的 start 值是多少 ?

我们修改代码如下:

public class Test {
    private int start = 0;
    public static void main(String[] args) {
        List<Integer> res = new ArrayList<>();
        for (int i = 0; i < 20; i++) {
            res.add(new Test().test());
        }
        System.out.println(res);
    }
    private int test() {
        Runnable runnable = () -> add();
        for (int i = 0; i < 10; i++) {
            Thread thread = new Thread(runnable);
            thread.start();
        }
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return start;
    }
    void add() {
        for (int i = 0; i < 10; i++) {
            start++;
        }
    }
}

查看控制台输出:

[100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100]

就不卖关子了,这里结果没问题的原因主要是因为 创建线程的耗时 比 add 方法执行的耗时还长, 所以就相当与单线程执行了,我们可以来验证下。

public class Test {
    private int start = 0;
    public static void main(String[] args) {
        new Test().test();
    }
    private int test() {
        for (int i = 0; i < 10; i++) {
            long t = System.nanoTime();
            Thread thread = new Thread(new TestRunnable(i));
            System.out.println(i + "_new_thred: " + (System.nanoTime() - t));
            thread.start();
        }
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return start;
    }
    void add() {
        for (int i = 0; i < 10; i++) {
            start++;
        }
    }
    private class TestRunnable implements Runnable {
        int id;
        public TestRunnable(int i) {
            id = i;
        }
        @Override
        public void run() {
            long t = System.nanoTime();
            add();
            System.out.println(id + "_add: " + (System.nanoTime() - t));
        }
    }
}

查看控制台输出:

0_new_thred: 1232700
1_new_thred: 31800
2_new_thred: 18000
3_new_thred: 24500
0_add: 62100
4_new_thred: 19700
5_new_thred: 76800
3_add: 19200
6_new_thred: 22300
7_new_thred: 24500
8_new_thred: 32000
9_new_thred: 26100
4_add: 23100
8_add: 20000
7_add: 18400
1_add: 20900
2_add: 19600
5_add: 40300
9_add: 22100
6_add: 23600

当我们修改 add 方法的次数为 10W 次之后:

public class Test {
    private int start = 0;
    public static void main(String[] args) {
        List<Integer> res = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            res.add(new Test().test());
        }
        System.out.println(res);
    }
    private int test() {
        Runnable runnable = () -> add();
        ExecutorService executorService = Executors.newFixedThreadPool(100);
        for (int i = 0; i < 100; i++) {
            executorService.execute(runnable);
        }
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        executorService.shutdown();
        return start;
    }
    void add() {
        for (int i = 0; i < 100000; i++) {
            start++;
        }
    }
}

查看控制台输出:

[9337838, 9957329, 10000000, 10000000, 10000000, 9925170, 10000000, 9922369, 10000000, 10000000]

修改上面的测试代码,给 start 添加 volatile 修饰符:

public class Test {
    private volatile int start = 0;
    public static void main(String[] args) {
        List<Integer> res = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            res.add(new Test().test());
        }
        System.out.println(res);
    }
    private int test() {
        Runnable runnable = () -> add();
        ExecutorService executorService = Executors.newFixedThreadPool(100);
        for (int i = 0; i < 100; i++) {
            executorService.execute(runnable);
        }
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        executorService.shutdown();
        return start;
    }
    void add() {
        for (int i = 0; i < 100000; i++) {
            start++;
        }
    }
}

查看控制台输出:

[2292403, 2449807, 2146843, 1899033, 2120498, 4689152, 2264998, 2181451, 2266435, 2443323]

可以发现结果也是不对的。


执行结果正确的代码

要正确输出结果我们可以修改代码如下:

public class Test {
    private int start = 0;
    public static void main(String[] args) {
        List<Integer> res = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            res.add(new Test().test());
        }
        System.out.println(res);
    }

    private int test() {
        Runnable runnable = () -> add();
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        for (int i = 0; i < 100; i++) {
            executorService.execute(runnable);
        }
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        executorService.shutdown();
        return start;
    }
    synchronized void add() {
        for (int i = 0; i < 100000; i++) {
            start++;
        }
    }
}

或者

public class Test {
    private AtomicInteger start = new AtomicInteger(0);
    public static void main(String[] args) {
        List<Integer> res = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            res.add(new Test().test());
        }
        System.out.println(res);
    }
    private int test() {
        Runnable runnable = () -> add();
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        for (int i = 0; i < 100; i++) {
            executorService.execute(runnable);
        }
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        executorService.shutdown();
        return start.get();
    }
    void add() {
        for (int i = 0; i < 100000; i++) {
            start.addAndGet(1);
        }
    }
}

或者

public class Test {
    private static ReentrantLock lock = new ReentrantLock();
    private int start = 0;

    public static void main(String[] args) {
        List<Integer> res = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            res.add(new Test().test());
        }
        System.out.println(res);
    }

    private int test() {
        Runnable runnable = () -> add();
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        for (int i = 0; i < 100; i++) {
            executorService.execute(runnable);
        }
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        executorService.shutdown();
        return start;
    }

    void add() {
        lock.lock();
        try {
            for (int i = 0; i < 100000; i++) {
                start++;
            }
        } finally {
            lock.unlock();
        }
    }
}

如果觉得不错的话,请帮忙点个赞呗。

以上


扫描下面的二维码,关注我的公众号 103Tech, 点关注,不迷路。

103Tech

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,928评论 6 509
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,748评论 3 396
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 166,282评论 0 357
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,065评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,101评论 6 395
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,855评论 1 308
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,521评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,414评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,931评论 1 319
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,053评论 3 340
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,191评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,873评论 5 347
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,529评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,074评论 0 23
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,188评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,491评论 3 375
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,173评论 2 357

推荐阅读更多精彩内容