在web应用中,一个请求(带有请求参数)就是一个线程,那么如何区分哪些参数属于哪个线程呢?比如struts中,A用户登录,B用户也登录,那么在Action中怎么区分哪个是A用户的数据,哪个是B用户的数据。这就涉及到ThreadLocal类了,将变量与当前线程绑定。比如struts中,有一个容器类,那么A用户将数据放在A的容器中,B用户将数据放在B的容器中,然后再将容器与线程绑定,这样的话,A请求的线程处理A容器的数据,B请求的线程处理B容器的数据,而不会混淆。
示例如下:
package ch03; import java.util.Random; public class ThreadLocalTest { public static void main(String[] args) {
Thread th = null;
for(int i=0; i<2; i++){
th = new Thread(new Runnable() {
@Override
public void run() {
int data = new Random().nextInt();
System.out.println(Thread.currentThread().getName()+"\t"+data);
Request request = Request.getThreadInstance();
request.setName("name:"+data);
request.setAge(data); //输出两个模块的值
new A().get();
new B().get();
}
});
th.start();
}
} /*A模块*/
static class A{
public void get(){
Request request = Request.getThreadInstance();
System.out.println("A: "+Thread.currentThread().getName()+"\t"+
request.getName()+"\t"+request.getAge());
}
}
/*B模块*/
static class B{
public void get(){
Request request = Request.getThreadInstance();
System.out.println("B: "+Thread.currentThread().getName()+"\t"+
request.getName()+"\t"+request.getAge());
}
} } class Request{ private Request(){} /*ThreadLocal:将变量与当前线程绑定,相当于Map<Thread, value>*/
private static ThreadLocal<Request> instance = new ThreadLocal<>();
/*返回当前线程的单例*/
public static Request getThreadInstance(){
Request request = instance.get();
if(request == null){
request = new Request();
instance.set(request);
}
return request;
} 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;
} }
输出结果: