用途
当前线程的存储信息,每个线程独享. 比如用户浏览访问的节点信息,保证访问节点与存储节点的一致.
代码:
下面用一个简单的案例来说明怎么使用ThreadLocal
package fx; /** * 线程存储工具类 * @author lxz * */ public class UserThreadLocalUtil { private static ThreadLocal<Integer> t1 = new ThreadLocal<Integer>();//存储年龄 private static ThreadLocal<String> t2 = new ThreadLocal<String>();//存储姓名 public static ThreadLocal<Integer> getT1() { return t1; } public static void setT1(ThreadLocal<Integer> t1) { UserThreadLocalUtil.t1 = t1; } public static ThreadLocal<String> getT2() { return t2; } public static void setT2(ThreadLocal<String> t2) { UserThreadLocalUtil.t2 = t2; } public static void main(String[] args) { Runnable thread1 = new Runnable() { public void run() { UserThreadLocalUtil.getT1().set(18); UserThreadLocalUtil.getT2().set("小明"); while(true){ System.out.println(UserThreadLocalUtil.getT1().get()); System.out.println(UserThreadLocalUtil.getT2().get()); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }; Runnable thread2 = new Runnable() { public void run() { UserThreadLocalUtil.getT1().set(20); UserThreadLocalUtil.getT2().set("小红"); while(true){ System.out.println(UserThreadLocalUtil.getT1().get()); System.out.println(UserThreadLocalUtil.getT2().get()); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }; Thread tt1 = new Thread(thread1); Thread tt2 = new Thread(thread2); tt1.start(); tt2.start(); } }
测试结果:
18
小明
20
小红
18
小明
20
小红
18
20
小红
小明
通过结果发现,即使调用的是static的工具类,两个线程获取的值互相不干扰.