volatile修饰的静态变量问题

来源:2-1 并发工具介绍

6095289

2020-04-06

老师我做力扣有道题我是通过volatile来控制并发访问的1114. 按序打印 但是volatile使用static修饰后为什么答案错误了想了好久没想明白

private volatile int flag = 1;

class Foo {
    /**
     * 线程 A   无需条件即可执行
     * 线程 B   flag = 2 可执行
     * 线程 C   flag = 3 可执行
     */
    private volatile int flag = 1;
    public Foo(){}
    public void first(Runnable printFirst) throws InterruptedException {
        printFirst.run();
        //标记线程2可以开始运行
        flag = 2;
    }
    public void second(Runnable printSecond) throws InterruptedException {
        //不满足空循环
        while (flag != 2){}
        printSecond.run();
        //标记线程3可以开始运行
        flag = 3;
    }
    public void third(Runnable printThird) throws InterruptedException {
        //不满足空循环
        while (flag != 3){}
        printThird.run();
    }
}

private static volatile int flag = 1;

class Foo {
    /**
     * 线程 A   无需条件即可执行
     * 线程 B   flag = 2 可执行
     * 线程 C   flag = 3 可执行
     */
    private static volatile int flag = 1;
    public Foo(){}
    public void first(Runnable printFirst) throws InterruptedException {
        //标记线程2可以开始运行
        printFirst.run();
        flag = 2;
    }
    public void second(Runnable printSecond) throws InterruptedException {
        //不满足空循环
        while (flag != 2){}
        printSecond.run();
        flag = 3;
    }
    public void third(Runnable printThird) throws InterruptedException {
        //不满足空循环
        while (flag != 3){}
        printThird.run();
    }
}
写回答

2回答

悟空

2020-04-06

给flag加上static,不应该影响代码的执行结果。

我认为代码没问题。

虽然提交的时候,提示答案错误:

//img1.sycdn.imooc.com/szimg/5e8b2c6909c6f61e10360742.jpg

但是我把同样的测试用例放到单次执行,结果是正确的:

//img.mukewang.com/szimg/5e8b2c5e096f20ed04840450.jpg

可能是leetcode的bug?

如果小伙伴有了新发现欢迎留言讨论。

我写的测试用例:

//img.mukewang.com/szimg/5e8b2b77092b8aa509182248.jpg


//img.mukewang.com/szimg/5e8b2b8709bb548806401992.jpg

1
2
悟空
回复
6095289
恩,你看下哈,测试用例单次执行的时候,结果是正确的。
2020-04-06
共2条回复

灵森

2020-04-06

能发下全部代码吗

0
3
6095289
回复
灵森
这里力扣题 你可以去看看再说 力扣题和其他题的风格有点不一样
2020-04-06
共3条回复

深度解密Java并发工具,精通JUC,成为并发多面手

JUC全方位讲解,构建并发工具类知识体系

1599 学习 · 573 问题

查看课程