Multithreading 06_ Zhang Xiaoxiang-threadlocal class and application skills

Source: Internet
Author: User

Use the Threadlocal class to implement thread-wide shared data:

Make sure that each thread has its own private variable and takes its own variable. The following is implemented using the Threadlocal class, instead of the map usage in the previous lesson

Code:

Package org.yla.thread;import java.util.random;/** * Implement thread-wide private data using the Threadlocal class * Replace the role of the previous lesson map * @author Huo_chai_gun * 20 December 18, 14 pm 3:25:35 */public class Threadlocaltest {private static threadlocal<integer> ThreadLocal = new Threadlocal<integer> ();p ublic static void Main (string[] args) {//Start two threads for (int i = 0; i < 2; i++) {New Thread (NE W Runnable () {@Overridepublic void Run () {//create each thread private variable int data = new Random (). Nextint (100); System.out.println (Thread.CurrentThread (). GetName () + "has put data:" +data);//Set Value Threadlocal.set (data) to local; new A (). get (); new B (). get ();}}). Start ();}} Static class A{public void Get () {int data =threadlocal.get (); System.out.println ("A from" +thread.currentthread (). GetName () + "have get data:" +data);}} Static class B{public void Get () {int data =threadlocal.get (); System.out.println ("B from" +thread.currentthread (). GetName () + "have get data:" +data);}}

Operation Result:

Thread-0 has put data:48thread-1 have put data:95a from Thread-1 have get data:95a from Thread-0 have get data:48b from T Hread-0 have get data:48b from Thread-1 have get data:95

Assuming that we have multiple threads that need to share data in scope, our code has to be changed to the following form: The idea is to package the values of other attributes into a class

Package org.yla.thread;import java.util.random;/** * Implement thread-wide private data using the Threadlocal class * Replace the role of the previous lesson map * @author Huo_chai_gun * 20 December 18, 14 pm 3:25:35 */public class Threadlocaltest {private static threadlocal<integer> ThreadLocal = new Threadlocal<integer> ();p rivate static threadlocal<mythreadlocalscopedate> mylocalscopedata = new  Threadlocal<mythreadlocalscopedate> ();p ublic static void Main (string[] args) {//Start two threads for (int i = 0; i < 2; i++) {New Runnable () {@Overridepublic void Run () {//Creates a variable that is private to each thread int data = new Random (). Nextint (100); System.out.println (Thread.CurrentThread (). GetName () + "has put data:" +data);//Set Value Threadlocal.set (data) to local; Mythreadlocalscopedate scopedate = new Mythreadlocalscopedate () scopedate.setname ("name" +data); ScopeDate.setAge ( data); Mylocalscopedata.set (scopedate); new A (). get (); new B (). get ();}). Start ();}} Static class A{public void Get () {int data =threadlocal.get (); System.out.println ("A from" +thread.currentthread (). GetName () + "HAs get data: "+data"); Mythreadlocalscopedate Scopedate=mylocalscopedata.get (); System.out.println ("A from" +thread.currentthread (). GetName () + "have get Mythreadlocalscopedate name:" + Scopedate.getname () + ", Age:" +scopedate.getage ());}} Static class B{public void Get () {int data =threadlocal.get (); System.out.println ("B from" +thread.currentthread (). GetName () + "have get data:" +data); Mythreadlocalscopedate Scopedate=mylocalscopedata.get (); System.out.println ("B from" +thread.currentthread (). GetName () + "have get Mythreadlocalscopedate name:" + Scopedate.getname () + ", Age:" +scopedate.getage ());}} Class Mythreadlocalscopedate{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.) {this.age = age;}}

Operation Result:

Thread-0 has put data:2thread-1 have put data:94a from Thread-1 have get data:94a from Thread-0 have get data:2a from Thr Ead-1 have get mythreadlocalscopedate name:name 94, age:94a from Thread-0 have get mythreadlocalscopedate name:name 2, AGE:2B from Thread-1 have get data:94b from Thread-0 have get data:2b from Thread-1 have get mythreadlocalscopedate name: Name 94, age:94b from Thread-0 have get mythreadlocalscopedate name:name 2, Age:2

Although the above code implements the function, but the code implementation is very garbage, a thread has an instance, then multiple threads have multiple instances, so we also have to modify the code:

Idea: Using singleton mode to achieve thread-wide shared data this will always be one object, but when each thread takes this object, we let him show the mutex effect. This saves content consumption and is invisible when externally called threadlocal the object is encapsulated


this should be a good design in real development . "Attention"

Code:

Package org.yla.thread;import java.util.random;/** * Implement thread-wide private data using the Threadlocal class * @author Huo_chai_gun * December 18, 2014 PM 3 : 25:35 */public class Threadlocaltest {private static threadlocal<integer> ThreadLocal = new threadlocal< Integer> ();p ublic static void Main (string[] args) {//Start two threads for (int i = 0; i < 2; i++) {New Thread (new Runnable () {@ overridepublic void Run () {//create each thread private variable int data = new Random (). Nextint (100); System.out.println (Thread.CurrentThread (). GetName () + "has put data:" +data);//Set the value to local threadlocal.set (data);// Gets the Mythreadlocalscopedate instance object of its own thread mythreadlocalscopedate MyData = Mythreadlocalscopedate.getthreadinstance (); Mydata.setname ("name" +data); mydata.setage (data); new A (). get (); new B (). get ();}}). Start ();}} Static class A{public void Get () {int data =threadlocal.get (); System.out.println ("A from" +thread.currentthread (). GetName () + "have get data:" +data); Mythreadlocalscopedate myData = Mythreadlocalscopedate.getthreadinstance (); System.out.println ("A from" +thread. CurrentThread (). GetName () + "have get Mythreadlocalscopedate name:" +mydata.getname () + ", Age:" +mydata.getage ());}} Static class B{public void Get () {int data =threadlocal.get (); System.out.println ("B from" +thread.currentthread (). GetName () + "have get data:" +data); Mythreadlocalscopedate myData = Mythreadlocalscopedate.getthreadinstance (); System.out.println ("B from" +thread.currentthread (). GetName () + "have get Mythreadlocalscopedate name:" +mydata.getname () + ", Age:" +mydata.getage ());}}} Class mythreadlocalscopedate{//Singleton mode private mythreadlocalscopedate () {};//Construction method privatization private static threadlocal< mythreadlocalscopedate> map = new threadlocal<mythreadlocalscopedate> ();// Encapsulation Mythreadlocalscopedate is a thread implementation in the range shared//think AB two threads come over the situation of their own analysis AB all need to have their own objects no relationship so do not need synchronization if there is a relationship, you need to synchronize the public static/* Synchronized*/mythreadlocalscopedate getthreadinstance () {mythreadlocalscopedate instance =map.get (); if (instance== NULL) {instance = new Mythreadlocalscopedate (); Map.set (instance);} return instance;} 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.) {this.age = age;}}

Operation Result:

Thread-0 has put data:24thread-1 have put data:13a from Thread-1 have get data:13a from Thread-1 have get Mythreadlocalsco  Pedate name:name13, age:13a from Thread-0 have get data:24a from Thread-0 have get mythreadlocalscopedate name:name24, age:24b from Thread-1 have get data:13b from Thread-1 have get mythreadlocalscopedate name:name13, age:13b from Thread -0 have get data:24b from Thread-0 have get mythreadlocalscopedate Name:name24, age:24



Multithreading 06_ Zhang Xiaoxiang-threadlocal class and application skills

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.