Thread Learning (eight) threadlocal implementing shared variables within the thread range

Source: Internet
Author: User
what is called thread-wide shared data (thread independent). A thread can call a module, B module, c module when it is running, for example we call A,b,c three objects, a,b,c three modules inside the code will access the outside variables, then if we put the variable ABC call to static variable, We can also get ABC to access the same variable at the same time, but if we use the second thread to call ABC at the same time to access the variable, then the second thread accesses the variable that is not the variable we accessed in thread 1 just now ... It's a different data, which means that the variable is the same when it is accessed by the same thread, and when we have a thread to access it, the data is not the same. So if we are 5 threads accessing this variable, then we get 5 different variables.
public class Threadscopsharedata {
	private static int data = 0;//We define a static variable data static
	
	class a{//define a static inner class
		public void GetData () {
			System.out.println (Thread.CurrentThread (). GetName () + "get data from a" +data);
		}
	
	The static class b{//defines a second static inner class public
		void GetData () {System.out.println () () () {
			thread.currentthread (). GetName () + " Get data from B "+data";
		}
	
	public static void Main (string[] args) {
		//Create two threads in the main function for
		(int i=1;i<3;i++) {
			new thread (new Runnable () {
				@Override public
				void Run () {
					data =new Random (). Nextint ();
					System.out.println (Thread.CurrentThread (). GetName () + "already set data" +data);
					New A (). GetData ();
					New B (). GetData ();
				}
			}). Start ();}}
We run the above program to find the result as follows Thread-0 has set the data 9296023
Thread-1 has set the data 979192099
Thread-0 get data from a 979192099
Thread-1 get data from a 979192099
Thread-0 get data from B 979192099
Thread-1 get data from B 979192099 thread 0 set and thread 0 The data obtained is different, so the data here does not implement the sharing within the thread. threadlocal is equivalent to a map
Now let's rewrite the above procedure.
public class Threadscopsharedata {
	private static int data = 0;//We define a static variable data
	private static map<thread, int eger> threaddata = new hashmap<thread,integer> ();
	The static class a{//defines a statically internal class public
		void GetData () {
			int data = Threaddata.get (Thread.CurrentThread ());
			System.out.println (Thread.CurrentThread (). GetName () + "get data from a" +data);
		}
	
	The static class b{//defines the second static inner class public
		void GetData () {
			int data = Threaddata.get (Thread.CurrentThread ());
			System.out.println (Thread.CurrentThread (). GetName () + "Get data from B" +data);
		}
	
	public static void Main (string[] args) {
		//Create two threads in the main function for
		(int i=1;i<3;i++) {
			new thread (new Runnable () {
				@Override public
				void Run () {
					int data =new Random (). Nextint ();
					Threaddata.put (Thread.CurrentThread (), data);
					System.out.println (Thread.CurrentThread (). GetName () + "already set data" +data);
					New A (). GetData ();
					New B (). GetData ();
				}
			}). Start ();}}


We create a map, then we create a local variable for each thread, and then we save the thread with the name list of the threads, so we get the following results Thread-1 has set the data-1254485186
THREAD-0 has set the data 1394718209
Thread-1 get data from a-1254485186
Thread-0 get data from a 1394718209
Thread-1 get data from B-1254485186
Thread-0 get data from B 1394718209
We find that this variable of thread 1 and thread 2 is independent of each other. ThreadLocalFirst threadlocal and the local thread does not have a dime relationship, not a special thread, it is just a thread of the local variable (in fact, a map), threadlocal for each thread that uses the variable to provide a separate copy of the variable, So each thread can change its own copy independently, without affecting the counterpart of other threads. In fact, this is in the space of time (contrary to synchronized), at the expense of memory, the single greatly reduce the thread synchronization (such as synchronized) the performance of the cost and reduce the complexity of the thread concurrency control. We change the above procedure to threadlocal implementation
public class Threadscopsharedata {
	private static threadlocal<integer> ThreadLocal = new threadlocal< Integer> ();
	public static void Main (string[] args) {
		//Create two threads in the main function for
		(int i=1;i<3;i++) {
			new Thread (new Runnable () {
				@Override public
				void Run () {
					int data =new Random (). Nextint ();
					Threadlocal.set (data);
					System.out.println (Thread.CurrentThread (). GetName () + "already set data" +data);
					New A (). GetData ();
					New B (). GetData ();
				}
			}). Start ();
			
		}
	The static class a{//defines a statically internal class public
		void GetData () {System.out.println () () (
			thread.currentthread). GetName () + " Get data from a "+threadlocal.get ()");
		}
	
	The static class b{//defines the second static internal class public
		void GetData () {
			threadlocal.get ();
			System.out.println (Thread.CurrentThread (). GetName () + "Get data from B" +threadlocal.get ());}
		}
	

Run results
THREAD-0 has set the data-732021060
Thread-1 has set the data 712253571
Thread-1 get data from a 712253571
Thread-0 get data from a-732021060
Thread-1 get data from B 712253571
Thread-0 get data from B-732021060

How multiple variables are stored with threadlocal. A threadlocal represents a variable, so how do you store it if you want to store multiple variables in one thread? At this point we can encapsulate multiple variables into an object and then store the object in threadlocal to achieve our needs.
Let's rewrite the code above so that our threadlocal can hold multiple variables, and each thread's threadlocal is independent.
/** * * * threadscopsharedata * Creator: LBM * Time: November 24, 2016-PM 3:03:03 * @version 1.0.0 * * */public class Threadsco
		psharedata {public static void main (string[] args) {A A = new A ();
		b b = new B ();
					Create two threads for (int i = 1; i < 3; i++) in the main function {new thread (new Runnable () {@Override public void run () {
					int data = new Random (). Nextint (); Localdata.getinstance (). setage (data);//Create your own object to hold the variable localdata.getinstance (). SetName ("name" +data);//Create your own object to store the variable Sy
					Stem.out.println (Thread.CurrentThread (). GetName () +data);
					A.getdata ();
				B.getdata ();

		}). Start (); } static Class A {//define a static internal class public void GetData () {localdata localdata =localdata.getinstance ();  Like to get variable System.out.println (Thread.CurrentThread (). GetName () + "get data from a" + "age===" + localdata.getage () + "name==="
		+ Localdata.getname ()); } static class B {//define the second static internal class public void GetData () {localdata localdata =localdata.getinstance ();/Create an object inside your thread to get the variable System.out.println (Thread.CurrentThread (). GetName () + "Get data from B" + "age===" + localdata.getage () +
		"name===" + localdata.getname ());
 }}/** * * * We call my object from anywhere on the thread and get an instance object associated with that thread. * Localdata * Creator: LBM * Time: November 24, 2016-PM 3:03:21 * @version 1.0.0 * */class Localdata {//Create an Object private Localdata ( {//Construction method Privatization} public static Localdata getinstance () {Localdata localdata = Threadlocal.get ();//When we are in the current thread from the Threadloc
			When the object is not in AL, we create a new object if (Localdata = = null) {Localdata = new localdata ();
		Threadlocal.set (Localdata);
	return localdata; //Create a ThreadLocal inside the object so that when each thread creates an object, it creates the object private static threadlocal<localdata> ThreadLocal =
	New Threadlocal<localdata> ();
	private String name;
	private int age;
	Public String GetName () {return name;
	public void SetName (String name) {this.name = name;
	public int getage () {return age;
	public void Setage (int age) {this.age = age; }

}


The objects we encapsulate above encapsulate the threadlocal inside this object, and then, through the idea of a single paradigm, we realize that regardless of where the thread is invoked, the object is the object associated with the threads. Each thread calls GetInstance to create an object, and it is judged whether the thread exists this object, if there is a direct return, if it does not exist, create a new object.

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.