ThreadLocal and static variables

Source: Internet
Author: User
Tags static class

Threadlocal is proposed to solve the concurrency problem of multithreaded routines, which can be called thread-local variables. The difference from a general variable is that the lifecycle is within the thread range.
The static variable is the same life cycle as the class, that is, the static variable exists as long as the class exists.
What would a static threadlocal be like?

Look at one of the following examples,

public class SequenceNumber {private static threadlocal<integer> Seqnum = new threadlocal<integer> () {public Integer InitialValue () {return 0;}}; public int Getnextnum () {Seqnum.set (Seqnum.get () + 1), return Seqnum.get (), public static void Main (string[) args) {sequ Encenumber sn = new SequenceNumber (); testclient T1 = new TestClient (SN); TestClient t2 = new TestClient (SN); testclient t3 = new TestClient (SN); T1.start (); T2.start (); T3.start (); T1.print (); T2.print (); T3.print (); private static class TestClient extends thread{private sequencenumber sn; public testclient (SequenceNumber sn) {this. sn = SN; public void Run () {for (int i=0; i< 3; i++) {System.out.println (Thread.CurrentThread (). GetName () + "-->" + sn.ge Tnextnum ()); } public void Print () {for (int i=0; i< 3; i++) {System.out.println (Thread.CurrentThread (). GetName () + "-->" + S N.getnextnum ()); } } } }

Here's the result.

Thread-2--> 1 Thread-2--> 2 Thread-2--> 3 Thread-0--> 1 Thread-0--> 2 Thread-0--> 3 Thread-1 ; 1 Thread-1--> 2 Thread-1--> 3 main--> 1 main--> 2 main--> 3 main--> 4 main--> 5 main--> 6 Main--> 7 main--> 8 main--> 9

You can see that the static threadlocal variable is a thread-related static variable, in which a static variable is referenced by each instance, but within a thread, the static variable is separated

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.