ThreadLocal为每个线程提供单独的数据副本,线程间的数据为自身线程所独有(不存在共享变量问题),直接看代码
1 public class ThreadLocalTest { 2 3 private static ThreadLocal<List<String>> threadLocal = new ThreadLocal<>(); 4 5 public void setThreadLocal(List<String> value) { 6 7 threadLocal.set(value); 8 } 9 10 public void getThreadLocal() { 11 12 threadLocal.get().foreach(name -> System.out.println(Thread.currentThread().getName()+"###" + name )); 13 } 14 15 16 public static void main(String[] args) { 17 18 final ThreadLocalTest test = new ThreadLocalTest(); 19 20 new Thread(new Runnable() { 21 @Override 22 public void run() { 23 List<String> strs = new ArrayList<String>(); 24 strs.add("1"); 25 strs.add("2"); 26 strs.add("3"); 27 t.setThreadLocal(strs); 28 t.getThreadLocal(); 29 } 30 },"t1").start(); 31 32 new Thread(new Runnable() { 33 34 @Override 35 public void run() { 36 List<String> strs = new ArrayList<String>(); 37 strs.add("a"); 38 strs.add("b"); 39 t.setThreadLocal(strs); 40 t.getThreadLocal(); 41 } 42 },"t2").start(); 43 } 44 45 }
t1 t2线程各自获取到自己的线程的所属的变量