发布于2021-05-29 22:54 阅读(826) 评论(0) 点赞(11) 收藏(2)
1、代码,第一个线程设置睡眠时间1秒钟,第二个线程设置睡眠时间0.5秒钟,为了方便查看结果。
package com.xz.thread.ThreadLocal;
/**
* @description: ThreadLocal实现每个线程管理各自的变量示例
* @author: xz
* @create: 2021-05-28 21:27
*/
public class Demo {
//实例化ThreadLocal,并初始化值为0
private ThreadLocal<Integer> count =new ThreadLocal(){
@Override
protected Integer initialValue() {
return new Integer(0);
}
};
//获取值的方法,值每次加1并返回
public int getNextValue(){
Integer value=count.get();
value++;
count.set(value);
return value;
}
//主方法测试
public static void main(String[] args) {
Demo d =new Demo();
//第一个线程
new Thread(new Runnable() {
@Override
public void run() {
while(true){
System.out.println(Thread.currentThread().getName()+" value="+d.getNextValue());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
//第二个线程
new Thread(new Runnable() {
@Override
public void run() {
while(true){
System.out.println(Thread.currentThread().getName()+" value="+d.getNextValue());
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
}
2、运行main函数,输出结果如下:
3、结论:
1、代码示例
package com.xz.thread.ThreadLocal;
/**
* @description:
* @author: xz
* @create: 2021-05-28 22:26
*/
public class Test {
private final static ThreadLocal<User> threadLocal = new ThreadLocal<User>();
//设置当前用户
public void setCurrentUser(User user) {
threadLocal.set(user);
}
//本地线程中取当前用户
public void getCurrentSystemUser() {
User user = threadLocal.get();
if (null == user) {
//执行代码
......
}
}
}
原文链接:https://blog.csdn.net/li1325169021/article/details/117375248
作者:小光头吃饭不用愁
链接:http://www.javaheidong.com/blog/article/207805/b3cd059847fc055e95f7/
来源:java黑洞网
任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任
昵称:
评论内容:(最多支持255个字符)
---无人问津也好,技不如人也罢,你都要试着安静下来,去做自己该做的事,而不是让内心的烦躁、焦虑,坏掉你本来就不多的热情和定力
Copyright © 2018-2021 java黑洞网 All Rights Reserved 版权所有,并保留所有权利。京ICP备18063182号-2
投诉与举报,广告合作请联系vgs_info@163.com或QQ3083709327
免责声明:网站文章均由用户上传,仅供读者学习交流使用,禁止用做商业用途。若文章涉及色情,反动,侵权等违法信息,请向我们举报,一经核实我们会立即删除!