您的位置:首页 > 其它

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变量定义在类的内部,由类自行管理,而线程只需要直接调用与其相关的实例即可。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: