
课程咨询: 400-996-5531 / 投诉建议: 400-111-8989
认真做教育 专心促就业
昆明IT培训的小编知道,ThreadLocal相当于一个Map<Thread, T>,各线程使用自己的线程对象Thread.currentThread()作为键存取数据,但ThreadLocal实际上是一个包装了这个Map,并且线程只能存取自己的数据,不能操作其它线程的数据。
T get()
set(T)
remove()
代码示例:
public static void main(String[] args) {
String[] names = new String[]{"A", "B", "C", "D", "E"};
for(int i=0; i<names.length; i++){
final String myName = names[i];
new Thread(){
public void run(){
name.set(myName);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
test();
}
}.start();
}
/*
运行结果:
Thread-0 ->我的名字叫A
Thread-2 ->我的名字叫C
Thread-1 ->我的名字叫B
Thread-3 ->我的名字叫D
Thread-4 ->我的名字叫E
*/
}
private static ThreadLocal<String> name = new ThreadLocal<String>();
public static void test(){
System.out.println(Thread.currentThread().getName() + " ->我的名字叫" + ame.get());
}