单从字面翻译更应该是本地化线程,而后倒是线程局部变量(ThreadLocalVariable)不是更合适吗?java
ThreadLocal究竟是用来干什么的喃?固然是保存线程私有的数据啊,因此一般变量是被修饰为private的。与局部变量不一样,一般是被定义为所有变量,而后它为全部线程都维护一份私有数据,具体实现方式就是为每个线程维护一个用Entity数组实现的Map数组
public T get() { Thread t = Thread.currentThread(); ThreadLocalMap map = getMap(t); if (map != null) { ThreadLocalMap.Entry e = map.getEntry(this); if (e != null) { @SuppressWarnings("unchecked") T result = (T)e.value; return result; } } return setInitialValue(); }
static class ThreadLocalMap { /** * The entries in this hash map extend WeakReference, using * its main ref field as the key (which is always a * ThreadLocal object). Note that null keys (i.e. entry.get() * == null) mean that the key is no longer referenced, so the * entry can be expunged from table. Such entries are referred to * as "stale entries" in the code that follows. */ static class Entry extends WeakReference<ThreadLocal<?>> { /** The value associated with this ThreadLocal. */ Object value; Entry(ThreadLocal<?> k, Object v) { super(k); value = v; } } /** * The initial capacity -- MUST be a power of two. */ private static final int INITIAL_CAPACITY = 16; /** * The table, resized as necessary. * table.length MUST always be a power of two. */ private Entry[] table; }
线程局部变量和线程共享数据区别在于一个用空间换时间,一个用时间换空间。后者用同步进行排队访问,而前者由于是独自维护的,不涉及同步问题ide
举例:this
package com.jv.java8.datetime; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import org.junit.Test; public class TestDateTime { @Test public void test1() { ThreadLocal<SimpleDateFormat> sdf = new ThreadLocal<SimpleDateFormat>() { protected SimpleDateFormat initialValue() { return new SimpleDateFormat("yyyyMMdd"); } }; //SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); Callable<Date> task = new Callable<Date>() { @Override public Date call() throws Exception { return sdf.get().parse("2018228"); } }; ExecutorService pool = Executors.newFixedThreadPool(5); List<Future<Date>> results = new ArrayList<>(); for(int i=0;i<10;i++) { results.add(pool.submit(task)); } results.stream().map(x->{ try { return x.get(); } catch (Exception e) { } return null; }).forEach(System.out::println); } }
对于代码中使用的Lambda表达式能够Java-Lambda表达式.net
对于设计的局部变量类型须要注意伪共享问题,能够参考伪共享线程