ThreadLocal即本地线程,被ThreadLocal修饰的变量会在每个线程的私有缓冲内复制一个完全相同的对象副本,从而避免了变量共享时候的线程安全问题
package thread.threadLocal;
public class ThreadLocalVariableTest {
private ThreadLocal<String> local = new ThreadLocal<String>();
public String getLocalValue(){
return local.get();
}
public void setLocalValue(String str){
local.set(str);
}
public static void main(String[] args) {
final ThreadLocalVariableTest test = new ThreadLocalVariableTest();
new Thread(new Runnable() {
@Override
public void run() {
test.setLocalValue("张三");
}
}).start();;
new Thread(new Runnable() {
@Override
public void run() {
System.out.println(test.getLocalValue());
}
}).start();
}
}
运行结果
null