Example of ThreadLocal in Android

Example of ThreadLocal in Android

Summary:

Demo Description:

ThreadLocal usage example

Official document description of ThreadLocal

Implements a thread-local storage,that is,a variable for which each thread has its own value.

All threads share the same ThreadLocal object,but each sees a different value when accessing it,

and changes made by one thread do not affect the other threads.

The implementation supports null values.

This paragraph describes the purpose of ThreadLocal:

1. For the same variable (i.e. the variable saved in ThreadLocal), its value is different for different threads

2 all threads share a ThreadLocal object, but different values are obtained when accessing the variables in the ThreadLocal object

When a thread modifies the variable value in ThreadLocal object, it will not affect other threads

for instance:

1 a ThreadLocal object (mThreadLocal) 2 is created in the main thread. The set () method calls the mThreadLocal in the main thread to save a string variable in mThreadLocal. In 3, the set () method calls the mThreadLocal in the two child thread, saves a string variable 4 to mThreadLocal, and calls get () in mThreadLocal in the main thread. Method gets the string variable saved for the main thread in mthreadlocal, and finds that its value remains unchanged

The use of ThreadLocal is well reflected in the looper class. It ensures that each thread corresponds to a looper one by one, and each looper is not affected

Example code:

Mainactivity is as follows:

Main.xml is as follows:

If you have any questions, please leave a message or go to the community of this site for exchange and discussion. Thank you for reading. I hope it can help you. Thank you for your support to this site!

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>