ThreadLocal usage and source code parsing, threadlocal source code

Source: Internet
Author: User

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();    }}
 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.