一.在线程池中使用
public class Test {
public static ThreadLocal<Integer> threadLocal = new ThreadLocal<>();
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(1);
executorService.execute(() -> {
threadLocal.set(20);
System.out.println(Thread.currentThread().getName() + ":" + threadLocal.get());
});
for (int i = 0; i < 10; i++) {
executorService.execute(() -> {
System.out.println(Thread.currentThread().getName() + ":" + threadLocal.get());
});
}
}
}
输出:
pool-1-thread-1:20
pool-1-thread-1:20
pool-1-thread-1:20
pool-1-thread-1:20
pool-1-thread-1:20
pool-1-thread-1:20
pool-1-thread-1:20
pool-1-thread-1:20
pool-1-thread-1:20
pool-1-thread-1:20
pool-1-thread-1:20
1.使用后删除
public class Test {
public static ThreadLocal<Integer> threadLocal = new ThreadLocal<>();
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(1);
executorService.execute(() -> {
threadLocal.set(20);
System.out.println(Thread.currentThread().getName() + ":" + threadLocal.get());
threadLocal.remove();
});
for (int i = 0; i < 10; i++) {
executorService.execute(() -> {
System.out.println(Thread.currentThread().getName() + ":" + threadLocal.get());
});
}
}
}
输出:
pool-1-thread-1:20
pool-1-thread-1:null
pool-1-thread-1:null
pool-1-thread-1:null
pool-1-thread-1:null
pool-1-thread-1:null
pool-1-thread-1:null
pool-1-thread-1:null
pool-1-thread-1:null
pool-1-thread-1:null
pool-1-thread-1:null
2.线程逻辑最开始删除
public class Test {
public static ThreadLocal<Integer> threadLocal = new ThreadLocal<>();
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(1);
executorService.execute(() -> {
threadLocal.remove();
threadLocal.set(20);
System.out.println(Thread.currentThread().getName() + ":" + threadLocal.get());
});
for (int i = 0; i < 10; i++) {
executorService.execute(() -> {
threadLocal.remove();
System.out.println(Thread.currentThread().getName() + ":" + threadLocal.get());
});
}
}
}
输出:
pool-1-thread-1:20
pool-1-thread-1:null
pool-1-thread-1:null
pool-1-thread-1:null
pool-1-thread-1:null
pool-1-thread-1:null
pool-1-thread-1:null
pool-1-thread-1:null
pool-1-thread-1:null
pool-1-thread-1:null
pool-1-thread-1:null