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