# 关于volatile的相关知识,主要阅读了一些文章
# 但是阅读了这些文章之后,总想着自己写写代码验证一下
public class QQ {
private static String name = "init";
private static boolean flag = false;
public static void main(String[] args) throws InterruptedException {
Thread thread1 = new Thread(() -> {
System.out.println("thread1 start");
name = "yukong";
flag = true;
System.out.println("thread1 end");
});
Thread thread2 = new Thread(() -> {
while (true) {
if (flag) {
System.out.println("flag = " + flag + ", name=" + name);
break;
}
}
});
thread2.start();
Thread.sleep(1000);
thread1.start();
}
}
- 上面代码的执行结果是thread1执行完成,thread2无输出,且一直在运行
# 我们使用上volatile
public class QQ {
private static String name = "init";
private volatile static boolean flag = false;
public static void main(String[] args) throws InterruptedException {
Thread thread1 = new Thread(() -> {
System.out.println("thread1 start");
name = "yukong";
flag = true;
System.out.println("thread1 end");
});
Thread thread2 = new Thread(() -> {
while (true) {
if (flag) {
System.out.println("flag = " + flag + ", name=" + name);
break;
}
}
});
thread2.start();
Thread.sleep(1000);
thread1.start();
}
}