一.在线程池中使用

  1. public class Test {
  2. public static ThreadLocal<Integer> threadLocal = new ThreadLocal<>();
  3. public static void main(String[] args) {
  4. ExecutorService executorService = Executors.newFixedThreadPool(1);
  5. executorService.execute(() -> {
  6. threadLocal.set(20);
  7. System.out.println(Thread.currentThread().getName() + ":" + threadLocal.get());
  8. });
  9. for (int i = 0; i < 10; i++) {
  10. executorService.execute(() -> {
  11. System.out.println(Thread.currentThread().getName() + ":" + threadLocal.get());
  12. });
  13. }
  14. }
  15. }
  16. 输出:
  17. pool-1-thread-1:20
  18. pool-1-thread-1:20
  19. pool-1-thread-1:20
  20. pool-1-thread-1:20
  21. pool-1-thread-1:20
  22. pool-1-thread-1:20
  23. pool-1-thread-1:20
  24. pool-1-thread-1:20
  25. pool-1-thread-1:20
  26. pool-1-thread-1:20
  27. pool-1-thread-1:20

1.使用后删除

  1. public class Test {
  2. public static ThreadLocal<Integer> threadLocal = new ThreadLocal<>();
  3. public static void main(String[] args) {
  4. ExecutorService executorService = Executors.newFixedThreadPool(1);
  5. executorService.execute(() -> {
  6. threadLocal.set(20);
  7. System.out.println(Thread.currentThread().getName() + ":" + threadLocal.get());
  8. threadLocal.remove();
  9. });
  10. for (int i = 0; i < 10; i++) {
  11. executorService.execute(() -> {
  12. System.out.println(Thread.currentThread().getName() + ":" + threadLocal.get());
  13. });
  14. }
  15. }
  16. }
  17. 输出:
  18. pool-1-thread-1:20
  19. pool-1-thread-1:null
  20. pool-1-thread-1:null
  21. pool-1-thread-1:null
  22. pool-1-thread-1:null
  23. pool-1-thread-1:null
  24. pool-1-thread-1:null
  25. pool-1-thread-1:null
  26. pool-1-thread-1:null
  27. pool-1-thread-1:null
  28. pool-1-thread-1:null

2.线程逻辑最开始删除

  1. public class Test {
  2. public static ThreadLocal<Integer> threadLocal = new ThreadLocal<>();
  3. public static void main(String[] args) {
  4. ExecutorService executorService = Executors.newFixedThreadPool(1);
  5. executorService.execute(() -> {
  6. threadLocal.remove();
  7. threadLocal.set(20);
  8. System.out.println(Thread.currentThread().getName() + ":" + threadLocal.get());
  9. });
  10. for (int i = 0; i < 10; i++) {
  11. executorService.execute(() -> {
  12. threadLocal.remove();
  13. System.out.println(Thread.currentThread().getName() + ":" + threadLocal.get());
  14. });
  15. }
  16. }
  17. }
  18. 输出:
  19. pool-1-thread-1:20
  20. pool-1-thread-1:null
  21. pool-1-thread-1:null
  22. pool-1-thread-1:null
  23. pool-1-thread-1:null
  24. pool-1-thread-1:null
  25. pool-1-thread-1:null
  26. pool-1-thread-1:null
  27. pool-1-thread-1:null
  28. pool-1-thread-1:null
  29. pool-1-thread-1:null