@Controller
@RequestMapping(value="test")
public class MyTest {
public List<Integer> list = new ArrayList<Integer>();
public ThreadLocal<List<Integer>> myThreadLocal= new ThreadLocal<List<Integer>>() {
protected java.util.List<Integer> initialValue() {
List<Integer> list = new ArrayList<Integer>();
return list;
};
};
@RequestMapping(value="my")
@ResponseBody
public String test(Integer id) {
list.add(id);
myThreadLocal.get().add(id);
System.out.println("threadLocal"+JsonUtil.toString(myThreadLocal.get()));
System.out.println(JsonUtil.toString(list));
return "OK";
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
每次http://localhost:8080/scs/test/my.action?id=9 id不一样
上图中之所以threadLocal对象也出现两个数字是因为两次请求线程池的同一个线程在处理,所以把上次请求的id保存下来了。
使用ThreadLocal要注意,多线程在线程池实现方式下会有此问题