package com.qimh.test;
public class ThreadLocalDemo {
ThreadLocal<Long> longLocal = new ThreadLocal<Long>();
ThreadLocal<String> stringLocal = new ThreadLocal<String>();
ThreadLocal<Long> startTime = new ThreadLocal<Long>();
ThreadLocal<Long> endTime = new ThreadLocal<Long>();
//普通变量值,会被修改
//String str = "";
ThreadLocal<String> str = new ThreadLocal<String>();
public void set() {
longLocal.set(Thread.currentThread().getId());
stringLocal.set(Thread.currentThread().getName());
startTime.set(System.currentTimeMillis());
//str = Thread.currentThread().getName();
str.set(Thread.currentThread().getName());
}
public long getLong() {
return longLocal.get();
}
public String getString() {
return stringLocal.get();
}
public long getStartTime(){
return startTime.get();
}
public static void main(String[] args) throws InterruptedException {
final ThreadLocalDemo test = new ThreadLocalDemo();
test.set();
System.out.println(test.getLong());
System.out.println(test.getString());
System.out.println(test.getStartTime());
System.out.println("str:" +test.str);
Thread thread1 = new Thread(){
public void run() {
test.set();
System.out.println(test.getLong());
System.out.println(test.getString());
System.out.println(test.getStartTime());
System.out.println((System.currentTimeMillis() - test.getStartTime() + "ms"));
try {
sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
};
};
thread1.start();
thread1.join();
System.out.println(test.getLong());
System.out.println(test.getString());
System.out.println((System.currentTimeMillis() - test.getStartTime() + "ms"));
System.out.println("str:" +test.str);
}
}
参考链接:https://www.cnblogs.com/dolphin0520/p/3920407.html