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回答
-
给flag加上static,不应该影响代码的执行结果。
我认为代码没问题。
虽然提交的时候,提示答案错误:
但是我把同样的测试用例放到单次执行,结果是正确的:
可能是leetcode的bug?
如果小伙伴有了新发现欢迎留言讨论。
我写的测试用例:
122020-04-06 -
灵森
2020-04-06
能发下全部代码吗
032020-04-06
相似问题