ThreadLocal
【小城贝尔】
线程自己有空间,存储数据保安全。
静态私有对象挂,方法存取初始化。
环境分析上下文,方法运行算本程。
子承父类半边天,数值仅是拷贝间。
package concurrently.ThreadLocal;
public class ThreadLocalDemo {
//官方建议私有静态 //静态私有对象挂
private static ThreadLocal<Integer> tl = new ThreadLocal<>();
//初始化一
private static ThreadLocal<Integer> tl1 = new ThreadLocal(){
@Override
protected Object initialValue() {
return 200;
}
};
//初始化方式二
private static ThreadLocal<Integer> tl2 = ThreadLocal.withInitial(()->500);
//子类inheritThradLocal
private static ThreadLocal<Integer> inheri = new InheritableThreadLocal<>();
public static void main(String[] args) {
System.out.println(tl2.get());
tl2.set(20);
System.out.println(tl2.get());
/*
500
20
*/
new Thread(()->{
System.out.println(tl2.get());
tl2.set(40);
System.out.println(tl2.get());
/*
500
40
*/
}).start();
new Thread(()->{
System.out.println(tl2.get());
tl2.set(330);
System.out.println(tl2.get());
/* 500
330*/
}).start();
new Thread(()->{
System.out.println("inheritable。。。"+inheri.get());
inheri.set(999);
System.out.println("inheritable。。。"+inheri.get());
/*
inheritable。。。null
inheritable。。。999
*/
new Thread(()->{
System.out.println("inheritable。。。inner "+inheri.get());
inheri.set(1110);
System.out.println("inheritable。。。iinner "+inheri.get());
/*
inheritable。。。inner 999 使用 InheritableThreadLocal 会继承拷贝父类的值
inheritable。。。iinner 1110
*/
}).start();
}).start();
}
}
class AnalyzeThreadContext{
public static void main(String[] args) {
new Thread(new ThreadDamo(),"ThreadContext").start();
/*
main =====> from constractor,,,
ThreadContext =====> run ......
*/
}
static class ThreadDamo implements Runnable{
ThreadDamo(){
System.out.println(Thread.currentThread().getName() +" =====> from constractor,,,");
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName() +" =====> run ......");
}
}
}