//爲線程局部變量設置初始值 static ThreadLocal<Object> threadLocal = new ThreadLocal<Object>() { @Override protected Object initialValue() { return "初始值"; } }; /** * 若是一個線程是從其餘某個線程中建立的,這個類將提供繼承的值 */ static ThreadLocal<Object> threadLocalII = new InheritableThreadLocal<Object>() { @Override protected Object childValue(Object o) { return "覆蓋繼承的值"; } }; public static void main(String args[]){ threadLocalII.set(new Integer(123)); Thread thread = new MyThread(); thread.start(); System.out.println("main = " + threadLocalII.get()); } static class MyThread extends Thread{ @Override public void run(){ System.out.println("MyThread = " + threadLocalII.get()); } }