ThreadLocal
public class ThreadLocalTest {
private static final ThreadLocal<Object> threadLocal = new ThreadLocal<Object>() {
// ThreadLocal没有被当前线程赋值时或当前线程刚调用remove方法后调用get方法,返回此方法值
protected Object initialValue() {
System.out.println("调用get方法时,当前线程共享变量没有设置,调用initialValue获取默认值!当前线程" + Thread.currentThread().getName());
return "";
};
};
public static void main(String[] args) {
new Thread(new MyThread()).start();
new Thread(new MyThread()).start();
new Thread(new MyThread()).start();
new Thread(new MyThread()).start();
}
public static class MyThread extends Thread {
@Override
public void run() {
for(int i = 0; i < 5; i++) {
if("".equals(threadLocal.get())) {
threadLocal.set("a");
}else {
threadLocal.set(threadLocal.get() + "a");
}
System.out.println("currentThread:" + Thread.currentThread().getName() + ":" + threadLocal.get());
}
}
}
}
Last updated