测试代码以下:tomcat
须要注意执行到构造函数和run方法当前的线程ID。以及在什么时候给ThreadLocal变量塞值。框架
package com.test.thread.local;
public class ThreadLocalTest {
//测试ThreadLocal
static ThreadLocal<String> threadLocalString = new ThreadLocal<String>();
static class Runer extends Thread{
public Runer(String name) {
//构造函数当前线程仍是主线程Id
System.out.println("Constructor Thread Id: " +Thread.currentThread().getId());
threadLocalString.set("[---Thread Id---]: " +Thread.currentThread().getId() );
}
@Override
public void run() {
//run方法中是新的线程Id
System.out.println("Runing fun Thread Id : " + Thread.currentThread().getId());
threadLocalString.set("[---Thread Id---]: " +Thread.currentThread().getId() );
System.out.println("(Int)>>>>" + threadLocalString.get());
}
}
public static void main(String args[]){
//主线程ID
System.out.println("Main Thread Id : " +Thread.currentThread().getId());
new Runer("runner").start();
System.out.println("(out)>>>>" + threadLocalString.get());
}
}ide
---------------函数
ThreadLocal set方法参照:测试
public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
}this
在struts,tomcat等框架中,都用到了ThreadLocal<>变量。线程
如这样可以获取get
ActionContext actionContext = ActionContext.getContext(); 也正是利用这样的特性io
正是利用了这样的特色class