Objective: How to ensure that the data on the respective thread is independent, that the data on a thread can only be manipulated by a thread
1: Sample thread sharing variable
Let's first look at a counter-example
Package Com.prepare.study;import java.util.random;/** * @author: YINLM * @Date: Created in 2018/4/18 * @Description: Multiple thread data Chaotic example */public class ThreadTest2 {//static modifier indicates that this is a global variable private static int data = 0; public static void Main (string[] args) {//impersonation has 3 threads for (int i=1;i<=3;i++) {new Thread (new Runna ble () {@Override public void run () {data = new Random (). Nextint (); System.out.println (Thread.CurrentThread (). GetName () + "put data" +data); Within the same thread scope to operate the shared data new Othera (). GetData (); New Otherb (). GetData (); }}). Start (); } }
Static class othera{public void GetData () {System.out.println (' A from ' + Thread.CurrentThread (). GetName () + "get" +data); }} static class otherb{public void GetData () {System.out.println (' B from ' + thread.currentthread (). GetName () + "get" +data); }}} Result: Data is messed up, Thread-0 put data, data from thread 0 is wrong Thread-0 put 830670045thread-1 put data-2139375952thread-2 put data-4585 33612A from Thread-2 get-458533612a from Thread-0 get-458533612a to Thread-1 get-458533612b from Thread-2 get-458533 612B from Thread-1 get-458533612b from Thread-0 get-458533612
Use the Threadlocal class thread binding to implement the thread independence of the data.
Package Com.prepare.study;import java.util.random;/** * @author: YINLM * @Date: Created in 2018/4/18 * @Description: */pub Lic class ThreadTest2 {//static modifier indicates that this is a global variable private static threadlocal<integer> Threaddata = new Threadloca L<> (); public static void Main (string[] args) {//impersonation has 3 threads for (int i=1;i<=3;i++) {new Thread (new Runna ble () {@Override public void run () {int data = new Random (). Nextint (); System.out.println (Thread.CurrentThread (). GetName () + "put data" +data); The data is thread-bound threaddata.set. New Othera (). GetData (); New Otherb (). GetData (); }}). Start (); }} static class othera{public void GetData () {//Gets the data System.out.println that the thread is bound to ( "A from" + Thread.CurrentThread (). GetName () + "Get" +threaddata.get ()); }} static class otherb{public void GetData () {System.out.println (' B from ' + Thread.currentt Hread (). GetName () + "Get" +threaddata.get ()); } }}
Use of 2:threadlocal
Threadlocal is used to implement data sharing within threads, that is, for the same program code, to share one piece of data while running on the same thread for each module, and to share another piece of data while running in another thread
(1) Each thread calls the global Threadlocal object's set method, which is equivalent to adding a record to its internal map, where key is the respective thread, and value is the values passed in by the respective set method. Can be called at the end of the thread
The Threadlocal.clear () method, which frees up memory faster and does not call, because the associated ThreadLocal variable can also be freed automatically after the thread ends
Summary: A thradlocal represents a variable, so it can only put one data, you have more than one variable to be thread-wide sharing, you want to define multiple Threadlocal objects, or it encapsulates these multiple variables into an object.
Tip One: Of course there is a more elegant way to write the object's construction method into thread-bound (that is, to have a class create a separate instance object for different threads), as in the following code.
Implement the encapsulation of the threadlocal variable, so that the outside world does not directly manipulate the threadlocal variable.
The design of this class mimics the idea of the simple interest pattern, simple interest is that all threads get the same instance, and this is each thread that gets its own independent object.
Package Com.prepare.study;import java.util.random;/** * @author: YINLM * @Date: Created in 2018/4/18 * @Description: */pub Lic class ThreadTest2 {public static void main (string[] args) {//impersonation has 3 threads for (int i=1;i<=3;i++) { New Thread (New Runnable () {@Override public void run () {int data = new Random (). Nextint (); System.out.println (Thread.CurrentThread (). GetName () + "put data" +data); The instance of the object is itself a thread-bound threadscopeuser.getthreadinstance (). SetName ("name-" +data); Threadscopeuser.getthreadinstance (). setage (data);
Simulation to manipulate data new Othera (). GetData (); New Otherb (). GetData (); }}). Start (); }} static class othera{public void GetData () {//Gets the thread-bound instance Threadscopeuser Scopeuser = Threadscopeuser.getthreadinstance (); System.out.println ("A from" + Thread.CurrentThread (). GetName () + "get" + scopeuser.getname () + "" +scopeuser.getage ()); }} static class otherb{public void GetData () {Threadscopeuser Scopeuser = threadscopeuser.ge Tthreadinstance (); System.out.println ("A from" + Thread.CurrentThread (). GetName () + "get" + scopeuser.getname () + "" +scopeuser.getage ()); }}}//The object is created to be thread independent, the thread independently manages the class threadscopeuser{private String name; Private Integer age; Construction method Private, modeled as a single case private Threadscopeuser () {}//So the instance object that gets the entity itself is thread-bound public static Threadscopeuser Getthreadinst Ance () {ThreadscopeuseR userinstance = Threadlocaluser.get (); if (userinstance = = null) {userinstance = new threadscopeuser (); Threadlocaluser.set (userinstance); } return userinstance; } private static threadlocal<threadscopeuser> Threadlocaluser = new threadlocal<> (); Public String GetName () {return name; } public void SetName (String name) {this.name = name; } public Integer Getage () {return age; public void Setage (Integer age) {this.age = age; }}
How to implement thread-scoped shared data--Threadlocall class and its application skills