Understanding of the Threadlocal class of concurrent Programming (II) __ Programming

Source: Internet
Author: User


Result: The 1~11 row describes the last set value of the GET, and 12 lines indicates that if the thread does not have the value that is initialized with the set value in the Threadlocal object, the gets is a null value if there is no reinitialization scheme;
The threadlocal value of the 1 Threada thread is: haha0
The threadlocal value of the 2 Threada thread is: HAHA1
The threadlocal value of the 3 Threada thread is: HAHA2
The threadlocal value of the 4 Threada thread is: HAHA3
The threadlocal value of the 5 Threada thread is: HAHA4
The threadlocal value of the 6 Threada thread is: HAHA5
The threadlocal value of the 7 Threada thread is: HAHA6
The threadlocal value of the 8 Threada thread is: haha7
The threadlocal value of the 9 Threada thread is: haha8
The threadlocal value of the Threada thread is: haha9
11 I get at the last value: HAHA9
The threadlocal value of the main thread is: 1513047722002


Note: The initialization value of this class is empty, the null value is obtained when the internal value is fetched directly with the Get method when no data is stored, and if you do not want to obtain a null value, you need to inherit the class and override its initialization method:

Package service;
Import java.util.Date;

public class Threadlocalext extends ThreadLocal {

    @Override
    protected Object initialvalue () {
        //return " I am the default and the first get is no longer null. ";
        return new Date (). GetTime ();
    }


Understanding three or one of usage is using threadlocal to write a tool class, the tool class as a box, so that different threads hold variables, and each thread can store its own variables, and the thread between the variables, Threadlocal class is to each thread to bind their own values:

Last Post: http://blog.csdn.net/weixin_38178584/article/details/78780544

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.