InheritableThreadLocal可以在子线程中取得父线程继承下来的值,即可以让子线程从父进程中取得值。
package org.github.lujiango; public class Test04 { static InheritableThreadLocal<String> itl = new InheritableThreadLocal<String>(); static class ThreadA extends Thread { @Override public void run() { try { System.out.println("ThreadA get: " + itl.get()); } catch (Exception e) { e.printStackTrace(); } } } public static void main(String[] args) { try { itl.set("Main"); Thread.sleep(1000); ThreadA a = new ThreadA(); a.start(); } catch (Exception e) { e.printStackTrace(); } } }
InheritableThreadLocal即可以设置默认值,也可以在继承父线程值的同时修改。
package org.github.lujiango; class InheritableThreadLocalExt extends InheritableThreadLocal<String> { @Override protected String initialValue() { return "defalut"; } @Override protected String childValue(String parentValue) { return parentValue + " child"; } } public class Test04 { static InheritableThreadLocalExt itl = new InheritableThreadLocalExt(); static class ThreadA extends Thread { @Override public void run() { try { Thread.sleep(1000); System.out.println("ThreadA get: " + itl.get()); } catch (Exception e) { e.printStackTrace(); } } } public static void main(String[] args) { try { System.out.println(itl.get()); itl.set("Main1"); Thread.sleep(1000); ThreadA a = new ThreadA(); a.start(); itl.set("Main2"); System.out.println(itl.get()); } catch (Exception e) { e.printStackTrace(); } } }
注:如果子线程在取得值得同时,主线程将InheritableThreadLocal中的值进行更改,那么子线程取到的值还是旧值。
时间: 2024-11-29 06:56:16