Java 中的ThreadLocal

What is ThreadLocal ?

1.ThreadLocal 是一個創建線程局部變量的類

2.通常情況下 ,一個對象中創建的變量是可以被任何一個線程訪問的,也就是共享變量,ThreadLocal 創建的變量只能被當前線程訪問,其他線程無法訪問和修改

Why is ThreadLocal ?


1.ThreadLocal  是爲了解決多線程資源共享訪問的問題,爲了讓每個線程中有自己本地獨立的實例且需要被多個方法調用,該變量在線程之間隔離,但是在方法和類之間可以共享

常用場景
1.JDBC中管理connection,藉助ThreadLocal ,當前線程操作的都是線程池中的同一個connection,保證了數據庫事物的正確性
2.避免常用的一些參數的傳遞,常用的信息Session,Cookie等維護到ThreadLocal 中,該線程中的方法都能訪問,而不需要參數傳遞

內部實現
ThreadLocal將變量的各個副本值保存在各個線程Thread對象實例裏面。而Thread對象實例是通過ThreadLocalMap數據結構來存儲副本值,ThreadLocalMap中存儲的是ThreadLocalMap.Entry,Entry實例是對ThreadLocal某個實例的弱引用

package com.app.demo.thread.threadlocal;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Run
{

    private static ThreadLocal<String> local = new ThreadLocal<>();
    
    public static void main(String[] args)
    {
        local.set("This is a threadlocal test ");

        Thread oThread = new Thread(new Runnable()
        {
            public void run()
            {
                System.out.println(Thread.currentThread().getName());
                System.out.println(local.get());
            }
        });

        ExecutorService executor = Executors.newFixedThreadPool(5);
        
        for (int i = 0; i < 10; i++)
        {
            executor.submit(oThread);
        }
       
        System.out.println("<--->"+Thread.currentThread().getName());
        
        System.out.println("<--->"+local.get());
        
        print();
    }

    public static void  print()
    {
        System.out.println("<-++-++->"+local.get());
    }
    
}
pool-1-thread-1
pool-1-thread-3
null
pool-1-thread-2
pool-1-thread-4
null
null
null
pool-1-thread-5
null
pool-1-thread-2
null
pool-1-thread-3
pool-1-thread-1
null
pool-1-thread-5
null
pool-1-thread-4
null
null
<--->main
<--->This is a threadlocal test 
<-++-++->This is a threadlocal test 

ThreadLocal 的參考文章

https://ylgrgyq.github.io/2017/09/21/java-threadlocal/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章