public class Test {
private static volatile int a = 65537;
public static void main(String[] args) {
new Thread(() -> {
while (true) {
if (a == 65538) {
a = 65537;
System.out.println("修改");
} else if (a == 65537) {
continue;
} else {
try {
throw new Exception("线程1出问题了"+a);
} catch (Exception e) {
e.printStackTrace();
break;
}
}
}
}).start();
new Thread(()->{
while (true) {
if (a == 65537) {
a = 65538;
System.out.println("修改");
} else if (a == 65538) {
continue;
} else {
try {
throw new Exception("线程2出问题了"+a);
} catch (Exception e) {
e.printStackTrace();
break;
}
}
}
}).start();
}
}
实验结果:
如果运行上述代码,出现以下两种情况:
修改
java.lang.Exception: 线程1出问题了65538
at cn.luckycurve.Test.lambda$main$0(Test.java:20)
at java.base/java.lang.Thread.run(Thread.java:834)
修改
修改
修改
修改
java.lang.Exception: 线程2出问题了65537
at cn.luckycurve.Test.lambda$main$1(Test.java:38)
at java.base/java.lang.Thread.run(Thread.java:834)