我将在本地线程中存储一个值持有者,并将其初始化为同一组所有线程的相同值持有者。
public class ThreadGroupLocal<T> extends ThreadLocal<ValueHolder> { private static class ValueHolder { public Object value; } // Weak & Concurrent would be even the better, but Java API wont offer that :( private static ConcurrentMap<ThreadGroup, ValueHolder> map = new ConcurrentHashMap<ThreadGroup, ValueHolder>; private static ValueHolder valueHolderForThread(Thread t) { map.putIfAbsent(t.getThreadGroup(), new ValueHolder()); return map.get(t.getThreadGroup()); } @Override protected ValueHolder initialValue() { return valueHolderForThread(Thread.currentThread()); } public T getValue() { (T) get().value; } public void setValue(T value) { get().value = value; } }然后使用
ThreadGroupLocal<String> groupLocal = new ThreadGroupLocal<String>(); groupLocal.setValue("foo"); //... String foo = groupLocal.getValue();确实(期望初始化)的执行与本地线程完全一样。



