ThreadLocal usage and source code parsing, threadlocal source code
ThreadLocal provides local variables of the thread. These variables are different from common variables. Each thread can access its own variables through the get or set method of ThreadLocal and initialize copies of variables independently. A ThreadLocal instance is usually a private static domain in other classes. It wants to associate its state with a thread.
Verify the isolation of thread Variables
Let's first write a test code:
public class ThreadTestActivity extends AppCompatActivity { private static final String TAG = "ThreadTestActivity "; private ThreadLocal
mStringThreadLocal = new ThreadLocal<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_acc); mStringThreadLocal.set("[Thread#main]"); Log.e(TAG, "[Thread#main] ThreadLocal String =" + mStringThreadLocal.get()); new Thread("Thread#1") { @Override public void run() { mStringThreadLocal.set("[Thread#1]"); Log.d(TAG, "[Thread#1] ThreadLocal String =" + mStringThreadLocal.get()); } }.start(); new Thread("Thread#2") { @Override public void run() { Log.d(TAG, "[Thread#1] ThreadLocal String =" + mStringThreadLocal.get()); } }.start(); }}