每个ThreadLocal实例代表一个局部变量
如下代码中所示,time变量为不同的线程设置了不同的睡眠时间。
package com.scott.current;
public class ThreadLocalDemo {
private static volatile ThreadLocal<String> userId = new ThreadLocal<>();
private static volatile ThreadLocal<Long> time = new ThreadLocal<>();
public static void main(String[] args) {
Runnable r = () -> {
String name = Thread.currentThread().getName();
while (true) {
if ("A".equals(name)) {
userId.set("foxtrot");
time.set(2000L);
} else {
userId.set("charlie");
time.set(5000L);
}
System.out.println(name + " " + userId.get());
try {
Thread.sleep(time.get());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
Thread thdA = new Thread(r);
thdA.setName("A");
Thread thdB = new Thread(r);
thdB.setName("B");
thdA.start();
thdB.start();
}
}