ThreadLocal基本原理及运用
2024-10-19 02:25:42
ThreadLocal提供本地线程变量。这个变量里面的值(通过get方法获取)是和其他线程分割开来的,变量的值只有当前线程能访问到,不像一般的类型比如Person,Student类型的变量,只要访问到声明该变量的对象,即可访问其全部内容,而且各个线程的访问的数据是无差别的。
static ThreadLocal<String> stringThreadLocal = new ThreadLocal<>(); @Test
public void test01(){
Thread thread1 = new Thread(){
@Override
public void run() {
stringThreadLocal.set("threadName===>"+Thread.currentThread().getName());
System.out.println(this.getName()+" thread get the value:"+stringThreadLocal.get()); }
};
Thread thread2 = new Thread(){
@Override
public void run() {
stringThreadLocal.set("threadName===>"+Thread.currentThread().getName());
System.out.println(this.getName()+" thread get the value:"+stringThreadLocal.get()); }
};
Thread thread3 = new Thread(){
@Override
public void run() {
stringThreadLocal.set("threadName===>"+Thread.currentThread().getName());
System.out.println(this.getName()+" thread get the value:"+stringThreadLocal.get());
}
}; thread1.start();
thread2.start();
thread3.start();
System.out.println("main线程调用set方法之前:"+stringThreadLocal.get());
stringThreadLocal.set("main 线程set的值");
System.out.println("main线程调用set方法之后:"+stringThreadLocal.get());
}
功能就是往线程里传值。
最新文章
- web前端面试题总结
- es5 and es6
- Codeforces 699
- AJAX验证用户是否存在
- static_cast 和 dynamic_cast 的区别
- RHEL 7.2 安装Oracle XE-11.2.0
- Android实战之你应该使用哪个网络库?
- UltraEdit for mac 3.2.0.10免费破解版下载!!
- [51nod1425]减减数
- BZOJ 4765: 普通计算姬 [分块 树状数组 DFS序]
- 获取GRIDVIEW中的TemplateField显示的文本值
- c#—get,set访问器的作用
- Mybatis映射文件的自动映射与手动映射问题
- 易度文档管理系统--http://www.everydo.com/
- Rhino学习教程——1.3
- Spark-shell错误:Missing Python executable &#39;python&#39;, defaulting to ...
- Java 强制类型转换(类转换注意事项)
- 从Java的角度简单修复Cookie越权漏洞
- Mybatis集成(转)
- Zookeeper单机伪集群