ThreadLocal的使用
2016-02-25 15:30
411 查看
用途
当前线程的存储信息,每个线程独享. 比如用户浏览访问的节点信息,保证访问节点与存储节点的一致.代码:
下面用一个简单的案例来说明怎么使用ThreadLocalpackage 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的工具类,两个线程获取的值互相不干扰.
相关文章推荐
- Android Monkey Test
- jsoup基础
- c语言入门之项目4.3——利用for循环求1-1/2*2+1/2*2*2...-1/2*2*2*2到2的8次方
- linux下mknod命令介绍
- android java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.pr
- 欢迎使用CSDN-markdown编辑器
- 数据库应用-XML数据存储(XML Speicherung)-2
- Windows下Nginx的启动、停止等命令
- char *ch = new char; 与 char *ch = new char[10];
- iOS开发系列--通讯录、蓝牙、内购、GameCenter、iCloud、Passbook系统服务开发汇总
- Spring代码分析一:加载与初始化
- Android异步消息处理机制完全解析,带你从源码的角度彻底理解
- iOS 添加,qq登陆,微信登陆,微博登陆,,步骤及其注意事项
- incredibuild 命令行 error D8037
- WebForm获取GET或者POST参数到实体的转换,ADO.NET数据集自动转换实体
- ORACLE里几种锁模式
- iOS支付宝支付,,,实现步骤及注意事项
- Memcached(一)在Windows上安装和测试memcached
- 如何做加载状态的监听。
- 判断两个数据库中不一样的表和存储过程