您的位置:首页 > 其它

ThreadLocal的使用

2016-02-25 15:30 411 查看

用途

当前线程的存储信息,每个线程独享. 比如用户浏览访问的节点信息,保证访问节点与存储节点的一致.

代码:

下面用一个简单的案例来说明怎么使用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的工具类,两个线程获取的值互相不干扰.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: