研究了一下volatile的作用,并用代码测试了一下,发现了一点疑问,先看代码:
测试1:空while循环体
class MyData {
int number = 0;
public void add() {
this.number += 10;
}
}
public class Test1 {
public static void main(String[] args) {
MyData my = new MyData();
new Thread(() -> {
System.out.println("start");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
my.add();
System.out.println(my.number);
System.out.println("end");
}).start();
while (my.number == 0) {
}
System.out.println("main " + my.number);
}
}
输出:
start
10
end
此时程序还在运行中,没停止,就是卡在while循环中,主线程的最后一条输出语句没有输出。
测试二:非空while循环体
class MyData {
int number = 0;
public void add() {
this.number += 10;
}
}
public class Test1 {
public static void main(String[] args) {
MyData my = new MyData();
new Thread(() -> {
System.out.println("start");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
my.add();
System.out.println(my.number);
System.out.println("end");
}).start();
while (my.number == 0) {
System.out.println();
}
System.out.println("main " + my.number);
}
}
在while中写上一些运行的代码
结果:
start
……很多空行
10
end
main 10
最终start后出现很多空行,最后while执行完毕
测试三:空while循环体+volatile
class MyData {
volatile int number = 0;
public void add() {
this.number += 10;
}
}
public class Test1 {
public static void main(String[] args) {
MyData my = new MyData();
new Thread(() -> {
System.out.println("start");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
my.add();
System.out.println(my.number);
System.out.println("end");
}).start();
while (my.number == 0) {
}
System.out.println("main " + my.number);
}
}
在mydate类的number添加volatile,并去掉while循环的代码
输出:
start
10
end
main 10
所以while有循环体且非volatile时为什么可以拿到正确答案而不会卡在while循环中?