package com.neutron.t19;
import java.util.concurrent.TimeUnit;
/**
* ThreadLocal线程局部变量
*/
public class T191 {
/*
* 为什么必须加上volatile?
* 虽然不加上volatile,得出的结果和目标结果一样,但是存在安全隐患,涉及到jvm原理
* 为了让变量在线程之间可见,必须要加上volatile
*/
static volatile Person person = new Person();
public static void main(String[] args) {
new Thread(() -> {
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(person.name);
}).start();
new Thread(() -> {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
person.name = "right";
}).start();
}
}
class Person {
String name = "guess";
}
thread26 - ThreadLocal1
最新推荐文章于 2024-06-15 20:17:46 发布