Java provides a type of threadlocal that has member variables of that type, and each thread that uses that variable retains a copy of the property's backup data, and the operation of that property inside the thread is the data that is backed up by itself. Therefore, member variables declared as threadlocal types are thread-safe.
A simple test of the difference between the members of the Threadlocal type and the ordinary members, in a multithreaded environment, each thread will have a threadlocal value, while the ordinary members are thread-shared.
Import Java.util.date;public class Mythreadlocal {private ThreadLocal date = new ThreadLocal ();p rivate Date d = Null;publi c void Process () {if (Date.get () ==null) {Date.set (new date ()); System.out.println ("<span style=" font-family:arial, Helvetica, Sans-serif; " >thread local fileld</span>: "+date.get ());}} Operation of the normal member requires synchronous processing of public void P () {synchronized (Mythreadlocal.class) {if (d==null) {d = new Date (); System.out.println ("ordinary field:" +d);}}}
Test class: Defines a Mythreadlocal object instance that accesses its method by 5 threads at the same time.
Import Java.util.date;public class Test {public static void main (string[] args) {final mythreadlocal t = new mythreadlocal (); for (int i = 0;i<5;i++) {Thread thread = new Thread () {public void run () {t.process (); T.P ();}}; Thread.Start ();} Date D1 = new Date ();D ate d2 = new Date (); System.out.println (D1==D2); System.out.println (D1.hashcode () ==d2.hashcode ());}}
Test results:
Falsetruethread local Fileld:fri Apr 14:47:30 CST 2015ordinary Field:fri Apr 14:47:31 CST 2015thread Local FILELD:FR I Apr 14:47:30 CST 2015thread local Fileld:fri Apr 14:47:30 CST 2015thread local FILELD:FRI Apr 14:47:30 CST 2015 Thread local FILELD:FRI Apr 14:47:30 CST 2015
Test Result Analysis: It is obvious that the shared member variable D was initialized only once by one thread, so the code for the P method was executed only once, and the threadlocal member variable, each thread that accesses the variable, creates a backup of the data, and the process method is executed five times. In addition, it is found that the hashcode of the objects obtained from the two Times New Date () is easily equal, but it is indeed two different objects.
The difference between Java Foundation-threadlocal variables and ordinary variables