一、ThreadLocal是指线程的局部变量,查看源码可以知道一个Map的方式。
package com.yezi.learn.local;
import java.util.Random;
/**
* Created by yezi on 2014/4/13.
*/
public class TestThreadLocal {
private static ThreadLocal<TLUser> threadLocal = new ThreadLocal<TLUser>();
public static void main(String []args){
for(int i=0;i<2;i++){
new Thread(
new Runnable() {
@Override
public void run() {
TLUser tlUser = new TLUser();
tlUser.setX(new Random().nextInt());
threadLocal.set(tlUser);
System.out.println("put"+tlUser);
new A().getData();
new B().getData();
}
}
).start();
}
}
static class A{
public void getData(){
System.out.println(Thread.currentThread().getName()+":"+threadLocal.get());
}
}
static class B{
public void getData(){
System.out.println(Thread.currentThread().getName()+":"+threadLocal.get());
}
}
}
class TLUser{
private int x;
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
@Override
public String toString() {
return ""+x;
}
}
二、ThreadLocal的第二种用法
package com.yezi.learn.local;
import java.util.Random;
/**
* Created by yezi on 2014/4/13.
*/
public class TestThreadLocal1 {
public static void main(String args[]){
for(int i=0;i<2;i++){
new Thread(new Runnable() {
@Override
public void run() {
ThreadScopeData.getThreadInstance().setName("xiaoyezi"+new Random().nextInt());
new A().outData();
new B().outData();
}
}).start();
}
}
static class A{
public void outData(){
System.out.println("A:"+Thread.currentThread().getName()+ThreadScopeData.getThreadInstance());
}
}
static class B{
public void outData(){
System.out.println("B:"+Thread.currentThread().getName()+ThreadScopeData.getThreadInstance());
}
}
}
class ThreadScopeData{
private ThreadScopeData(){}
private String name;
private static ThreadLocal<ThreadScopeData> threadLocal = new ThreadLocal<ThreadScopeData>();
public static ThreadScopeData getThreadInstance(){
ThreadScopeData threadScopeData = threadLocal.get();
if(threadScopeData==null){
threadScopeData = new ThreadScopeData();
threadLocal.set(threadScopeData);
}
return threadScopeData;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return name;
}
}
三、总结
1、ThreadLocal是使用的一种线程的局部变量。
2、使用ThreadLocal可以很好每次都使用开始创建的那个对象。
3、Hibernate中就使用ThreadLocal来获取当前事务的处理。