volatile的可见性(代码实现)
package now;
import java.sql.Time;
import java.util.concurrent.TimeUnit;
class Student{
int age = 0;
//volatitle int age = 0;
public void changeage(){
this.age = 50;
}
}
/**
* 验证volatile的可见性
* 假如 int age = 0; age变量前面没有用volatile 关键字 修饰
* volatile可以保证可见性,及时通知其他线程,主物理内存的值已经被修改
*/
public class VolatileTest {
public static void main(String[] args) { //main是一切方法的运行入口
Student student = new Student(); //学生类
// AAA 第一个线程
new Thread(() -> {
System.out.println(Thread.currentThread().getName() + "\t come in");
//暂停一会线程
try { TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) { e.printStackTrace(); }
student.changeage();
System.out.println(Thread.currentThread().getName() + "\t change age to " + student.age);
}, "AAA").start();
// main 第二个线程
while(student.age == 0){
//main线程 循环等待student.age的变化 知道age不等于0
}
System.out.println(Thread.currentThread().getName() + "\t mission over" + student.age);
}
}
main线程跳不出循环
当age用volatile关键字修饰之后
main线程能够跳出循环