public static void main(String[] args) throws InterruptedException { ThreadLocal<String> threadLocal = new ThreadLocal<String>(){ @Override protected String initialValue() { return "设置默认值"; } }; System.out.println(threadLocal.get()); }结果:
设置默认值 java
2.ThreadLocal是隔离每一个线程的。但若是想要在子线程中取得主线程中的值,就要使InheritableThreadLocal。如: ide
private static InheritableThreadLocal<String> shareLocal = new InheritableThreadLocal<String>(); public static void main(String[] args) throws InterruptedException { shareLocal.set("main set : hello"); new Thread(){ public void run() { System.out.println(shareLocal.get()); }; }.start(); }
结果:
main set : hello spa