Android ThreadLocal★

1.ThreadLocal

ThreadLocal is a data storage class inside a thread, through which data can be stored in a specified thread. After the data is stored, it can only be accessed in the specified thread, and other threads cannot obtain it. Therefore, when multiple threads are executing, in order not to interfere with each other's resources, ThreadLocal can be used.

 

scenes to be used:

① When some data is scoped to threads and different threads have different data copies, you can consider using ThreadLocal.

In Android's Handler message mechanism, the scope of Looper is threads and different threads have different Loopers. Here, ThreadLocal is used to associate Looper with threads. If ThreadLocal is not used, the system must provide a global Hash table. Looper for Handler to find the specified thread, which is much more complicated than ThreadLocal.

②ThreadLocal can also be considered when transferring objects under complex logic.

For example, the task executed in a thread is more complicated, and a listener is needed to run through the execution process of the entire task. If ThreadLocal is not used, then the listener needs to be passed from the function call stack layer by layer, which is impossible for program design. Accepted, at this time, you can use ThreadLocal to make the listener exist as a global object in the thread, and you only need to get the listener through the get method inside the thread. Each listener object is stored internally in its own thread.

 

2. ThreadLocal usage

public class MainActivity extends Activity {

    private ThreadLocal<Object> mThreadLocal = new ThreadLocal<>();

    @Override

    protected vo

Guess you like

Origin blog.csdn.net/zenmela2011/article/details/127524346