ThreadLocal & Inheritable ThreadLocal에서 사용하는 구덩이

2726 단어 다중 스레드
  • ThreadLocal은 스레드 풀과 함께 사용할 때 데이터 재사용
  • 이 발생할 수 있음
               ,                       ,             run  。   ThreadLocal     ,    remove  。
    
    public class B {
         static final ThreadLocal threadParam = new ThreadLocal<>();
         public static void main(String[] args) throws InterruptedException {
             //        3   
             ExecutorService execService = Executors.newFixedThreadPool(3);
             //           
             while (true) {
                 Thread t = new Thread(()->{
                         threadParam.set("abc");
                         System.out.println("t1:" + threadParam.get());
                         //     remove,      //                    threadParam.remove();
                 });
                 execService.execute(t);
                 TimeUnit.SECONDS.sleep(1);
                 Thread t2 = new Thread(()-> {
                         System.out.println("t2:" + threadParam.get());
                 });
                 execService.execute(t2);
             }
         } }
    
  • InheritableThreadLocal과 스레드 풀을 결합하여 사용할 때 부모 스레드를 공유하는 InhertiableThreadLocal
  • 이 나타납니다
    public static void main(String[] args) throws InterruptedException {
            //        3   
            ExecutorService execService = Executors.newFixedThreadPool(3);
            //           
            while (true) {
                //  1,        
                Thread t = new Thread(()->{
                    threadParam.set("abc");
                    System.out.println("t1:" + threadParam.get());
                    Thread t2 = new Thread(()->{
                        System.out.println("t2:" + threadParam.get());
    //                        threadParam.remove();
                    });
                    execService.execute(t2);
    
                    Thread t3 = new Thread(()->{
                        System.out.println("t3:" + threadParam.get());
    //                        threadParam.remove();
                    });
                    execService.execute(t3);
    
                    Thread t4 = new Thread(()->{
                        System.out.println("t4:" + threadParam.get());
    //                        threadParam.remove();
                    });
                    execService.execute(t4);
    
                });
                execService.execute(t);
                TimeUnit.SECONDS.sleep(1);
                //  4,  1  
                Thread t5 = new Thread(()-> {
                    threadParam.set("CBA");
                    System.out.println("t5:" + threadParam.get());
                });
                execService.execute(t5);
            }
        }
    

    Another case see the below link: https://blog.csdn.net/Sunfj0821/article/details/81349775

    좋은 웹페이지 즐겨찾기