ThreadLocal使用小技巧
2015-09-24 10:09
211 查看
大家都知道使用ThreadLocal可以使对象达到线程隔离的目的。
在使用ThreadLocal可以不用单独定义一个变量用于保存和线程相关的属性,这样若出现多个与线程相关的变量也就要定义多个ThreadLocal。
与其这样定义,不如定义一个专门和线程进行绑定的类,自身进行管理ThreadLocal,已达到我们的要求。
import java.util.Random;
public class ThreadLocalDemo
{
public static void main(String[] args)
{
for (int i = 0; i < 2; i++)
{
new Thread(new Runnable()
{
@Override
public void run()
{
int data = new Random().nextInt();
System.out.println(Thread.currentThread().getName() + " put " + data);
Person.getInstance().setName("zhangsan:" + data);
Person.getInstance().setAge(data);
System.out.println(Thread.currentThread().getName() + " get name-" + Person.getInstance().getName()
+ " age-" + Person.getInstance().getAge());
}
}).start();
}
}
}
class Person
{
static ThreadLocal<Person> threadLocal = new ThreadLocal<Person>();
private Person()
{
}
public static Person getInstance()
{
Person person = threadLocal.get();
if (person == null)
{
person = new Person();
threadLocal.set(person);
}
return person;
}
private String name;
private int age;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public int getAge()
{
return age;
}
public void setAge(int age)
{
this.age = age;
}
}
把ThreadLocal变量定义在类的内部,由类自行管理,而线程只需要直接调用与其相关的实例即可。
在使用ThreadLocal可以不用单独定义一个变量用于保存和线程相关的属性,这样若出现多个与线程相关的变量也就要定义多个ThreadLocal。
与其这样定义,不如定义一个专门和线程进行绑定的类,自身进行管理ThreadLocal,已达到我们的要求。
import java.util.Random;
public class ThreadLocalDemo
{
public static void main(String[] args)
{
for (int i = 0; i < 2; i++)
{
new Thread(new Runnable()
{
@Override
public void run()
{
int data = new Random().nextInt();
System.out.println(Thread.currentThread().getName() + " put " + data);
Person.getInstance().setName("zhangsan:" + data);
Person.getInstance().setAge(data);
System.out.println(Thread.currentThread().getName() + " get name-" + Person.getInstance().getName()
+ " age-" + Person.getInstance().getAge());
}
}).start();
}
}
}
class Person
{
static ThreadLocal<Person> threadLocal = new ThreadLocal<Person>();
private Person()
{
}
public static Person getInstance()
{
Person person = threadLocal.get();
if (person == null)
{
person = new Person();
threadLocal.set(person);
}
return person;
}
private String name;
private int age;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public int getAge()
{
return age;
}
public void setAge(int age)
{
this.age = age;
}
}
把ThreadLocal变量定义在类的内部,由类自行管理,而线程只需要直接调用与其相关的实例即可。
相关文章推荐
- redis监控软件,redis-stat安装
- flume1.4.0 保存文件到hdfs错误调试
- JAVA编码总结
- Netty系列之Netty高性能之道
- BigDecimal --判断两数相除是否为无穷
- flume1.4.0 保存文件到hdfs错误调试
- linux下分别使用lipcap和socket抓包分析包
- IP地址
- Android之Handler用法总结
- KMP算法java
- Linux 朝花夕拾
- 关于hibernate的merge、attachDirty、attachClean方法的应用
- 认识真实的自己
- [刷题]Maximum Subarray III
- 堆和栈
- JavaScript中尺寸、坐标
- 关东升给的ios学习路线图(可以借鉴)
- IOS配置支付宝
- JSP中的errorPage和isErrorPage
- 利用UIView上手势控制OpenGL的绘制