public static void threadLocal() {
ThreadLocal<String> local = new ThreadLocal<>();
IntStream.range(0, 10).forEach(i -> new Thread(() -> {
local.set(Thread.currentThread().getName() + ":" + i);
System.out.println("线程:" + Thread.currentThread().getName() + ",local:" + local.get());
}).start());
}
package cn.netkiller.thread;
public class ThreadLocaTest {
private static ThreadLocal<String> local = new ThreadLocal<String>();
public static void main(String[] args) throws InterruptedException {
new Thread(new Runnable() {
public void run() {
System.out.println(Thread.currentThread().getName() + ":" + local.get());
ThreadLocaTest.local.set("thread_A");
System.out.println(Thread.currentThread().getName() + ":" + local.get());
}
}, "A").start();
Thread.sleep(1000);
new Thread(new Runnable() {
public void run() {
System.out.println(Thread.currentThread().getName() + ":" + local.get());
ThreadLocaTest.local.set("thread_B");
System.out.println(Thread.currentThread().getName() + ":" + local.get());
local.remove();
System.out.println("remove: " + local.get());
}
}, "B").start();
}
}
package cn.netkiller.test;
public class Test {
public static void main(String[] args) {
System.out.println(Thread.currentThread());
try (var ctx = new UserContext("Bob")) {
// 可任意调用UserContext.currentUser():
String currentUser = UserContext.currentUser();
System.out.println(currentUser);
} // 在此自动调用UserContext.close()方法释放ThreadLocal关联对象
}
public static class UserContext implements AutoCloseable {
static final ThreadLocal<String> ctx = new ThreadLocal<>();
public UserContext(String user) {
ctx.set(user);
}
public static String currentUser() {
return ctx.get();
}
@Override
public void close() {
ctx.remove();
}
}
}