The use of multi-threaded learning threadlocal.

Source: Internet
Author: User

ThreadLocal, the thread variable, is a ThreadLocal object as the key, and any object is worth the storage interface. This interface is attached to the thread, which means that a thread can query a Threadlocal object to the value that is bound on the threads.

You can set a value by using the Set (T) method, under the current thread, by getting the value that was originally set by the Get () method.

is the text above a bit obscure? Come on, learn to understand.

Variables worth sharing can be in the form of public static variables, with all threads using the same public static variable. If you want to implement each thread has its own shared variables how to solve that?

The JDK provides the threadlocal to solve this problem.

The main solution of class threadlocal is that each thread binds its own value, and the Threadlocal class can be likened to a box that holds data globally, and the box can store private data for each thread.

  

The following experiment:

1 Create a Threadlocal object that stores the private values for each thread.

  

public class Tools {public static ThreadLocal t=new ThreadLocal ();}

2 Create two threads, a, B.

  

public class Threada extends Thread {@Overridepublic void run () {super.run (), try {for (int i=0;i<100;i++) {Tools.t.set ( "Threada" + (i+1)); System.out.println ("Threada get Value" + tools.t.get ()); Thread.Sleep (200);}} catch (Exception e) {e.printstacktrace ();}}}

  

public class Threadb extends thread{@Overridepublic void Run () {super.run (), try {for (int i=0;i<100;i++) {Tools.t.set ( "THREADB" + (i+1)); System.out.println ("Threadb Get Value" +tools.t.get ()); Thread.Sleep (200);}} catch (Exception e) {e.printstacktrace ();}}}

Main thread:

public class Run {public static void main (string[] args) {try {Threada a=new Threada (); THREADB b=new threadb (); A.start (); B.start (); for (int i = 0; i <; i++) {Tools.t.set ("main" + (i+1)); System.out.println ("Main Get Value" +tools.t.get ()); Thread.Sleep (200);}} catch (Exception e) {e.printstacktrace ();}}}

Console:

THREADB Get value threadb 1ThreadA get value Threada 1main get value main 1ThreadA get value Threada 2main get value Main 2ThreadB Get value threadb 2main get value main 3ThreadA get value Threada 3ThreadB get value threadb 3ThreadA get value T Hreada 4ThreadB Get value threadb 4main get value main 4ThreadB get value threadb 5ThreadA get value Threada 5main get Val UE main 5main Get value main 6ThreadB get value threadb 6ThreadA get value Threada 6

It can be found that threada,threadb, and the main thread three in the threadlocal stored in the value of each other, each thread increment, value, are their own private. The values stored in the threadlocal are isolated.

Use the class Inheritablethreadlocal class to get the values from the parent thread in the child thread and modify it.

The following uses threadlocal to simulate the problem of counting five threads to go through a period of code consumption.

Start by creating a common profiler class

  

The public class Profiler {//First get () method calls are initialized (provided the Set method is not called), and each thread is called once. private static final threadlocal<long> time_threadlocal=new threadlocal<long> () {protected Long InitialValue () {return System.currenttimemillis ();};}; public static final void begin () {Time_threadlocal.set (System.currenttimemillis ());} public static final Long end () {return System.currenttimemillis ()-time_threadlocal.get ();}}

The main thread opens five threads and calls the Begin () and end () methods. (For cases where the call to get returns is null without calling set, the comment has been interpreted to resolve the workaround.) You can also change the initialized value by inheriting the Threadlocal class and then overriding the InitialValue () method);

  

public class Run {public static void main (string[] args) {for (int i = 0; i < 5; i++) {final int temp=i; Thread Thread=new Thread (new Runnable () {@Overridepublic void run () {try {profiler.begin (); Thread.Sleep (temp*1000); SYSTEM.OUT.PRINTLN ("Thread" +thread.currentthread (). GetName () + "time consuming      " +profiler.end ());} catch (Exception e) { E.printstacktrace ();}}); Thread.Start ();}}}

Console:

Thread Thread-0 consume time      0 thread Thread-1 consume time      1000 thread Thread-2 consume time      2000 thread Thread-3 consume time      3001 thread Thread-4 consume time      4001

It can be found that five threads do not affect each other and each counts their own time spent.

  Every good person has a silent time. No complaining, no complaints, finally through the passage of the time to move their own days.

  

The use of multi-threaded learning threadlocal.

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.