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循环中,主线程的最后一条输出语句没有输出。
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执行完毕
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循环中?
你把while循环体的print语句改成别的语句就知道了
因为print会发生同步(同步输出设备),所以没有volatile也会因为同步而刷新线程内存
所以加volatile是正确的,while加循环体只是你用了print的侥幸