測試代碼以下: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