基本的ThreadLocal使用
public class ThreadLocalTest {
static ThreadLocal tl=new ThreadLocal();
public static void main(String[] args) {
for(int i=0;i<2;i++){
new Thread(new Runnable(){
int data =new Random().nextInt();
public void run() {
System.out.println(Thread.currentThread().getName()+"存入的数据是 "+data);
tl.set(data); //存到了当前线程
new A().getThreadData();
}
}).start();
}
}
static class A{ //静态类相当于一个外部类
public void getThreadData(){
System.out.println("data is "+tl.get());
}
}
}
结果可能是
Thread-0存入的数据是 1997234255
Thread-1存入的数据是 267171693
data is 1997234255
data is 267171693
通过包装对象非常烂的使用方式
class MyThreadScopeData{
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;
}
}
public class ThreadLocalTest {
static ThreadLocal<MyThreadScopeData> myThreadScopeData=
new ThreadLocal<MyThreadScopeData>();
public static void main(String[] args) {
for(int i=0;i<2;i++){
new Thread(new Runnable(){
int data =new Random().nextInt();
public void run() {
MyThreadScopeData mydata=new MyThreadScopeData();
mydata.setName("name is name"+data);
mydata.setAge(data);
//把对象存入ThreadLocal 这样的做法非常烂!!!!!
myThreadScopeData.set(mydata);
new B().showThreadScopeData();
}
}).start();
}
}
static class B{
public void showThreadScopeData(){
System.out.println(myThreadScopeData.get().getName());
System.out.println("age is "+myThreadScopeData.get().getAge());
}
}
}
}
标准使用方式
/**
* 单列线程
* 在线程中范围内任意地方调,得到都是同一个实例对象
* 把ThreadLocal封装到单列的内部
*/
class ThreadSingle{
private ThreadSingle(){}
public static ThreadLocal<ThreadSingle> map=new ThreadLocal<ThreadSingle>();
//不需要加synchronized,即便有第2个线程进入,但拿到的map.get()是独有的。
public static ThreadSingle getThreadInstance(){ //方法得到是与本线程相关的实例
ThreadSingle obj=map.get();
/**
* 如果A进入时obj=null,刚创建完还没赋值,此时B线程进入,但B和A没有关系。
*/
if(obj==null){
obj=new ThreadSingle();
map.set(obj);
}
return obj;
}
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;
}
}
public class ThreadLocalTest {
public static void main(String[] args) {
for(int i=0;i<2;i++){
new Thread(new Runnable(){
int data =new Random().nextInt();
public void run() {
ThreadSingle.getThreadInstance().setName("name"+data);
ThreadSingle.getThreadInstance().setAge(data);
new C().showData();
}
}).start();
}
}