Package thread;
Import Java.util.Random; The public class Threadlocalsharedatademo {/** * threadlocal class and application techniques encapsulate the shared data within a thread, encapsulate it in a separate data class, and provide a set fetch method * The class is instantiated to provide an instance Object is an object that is already encapsulated within the current thread scope * * @param args */public static void main (string[] args) {for (int i = 0; I &l T 2;
i++) {New Thread (new Runnable () {@Override public void run () {int data = new Random (). Nextint (889);
System.out.println (Thread.CurrentThread (). GetName () + "Generate Data: +");
MyData MyData = Mydata.getinstance ();
Mydata.setage (data);
Mydata.setname ("Name:" + data);
New A (). get ();
New B (). get ();
}). Start ();
} static class A {//Can call the corresponding method String name = Mydata.getinstance () directly using an object instance within the scope of the thread being fetched. GetName ();
int age = Mydata.getinstance (). Getage ();
public void Get () {System.out.println () Thread.CurrentThread () GetName () +--AA Name: "+ name +" ... Age: "+ age"; } static class B {//can invoke the corresponding method String name by directly using the object instance within the range of the thread being fetchedMydata.getinstance (). GetName ();
int age = Mydata.getinstance (). Getage ();
public void Get () {System.out.println () Thread.CurrentThread (). GetName () + "--BB Name:" + name + "... Age:" + age "; } static class MyData {//Storing instance objects in the current thread scope data set static threadlocal<mydata> ThreadLocal = new threadlocal<
Mydata> ();
Single Case Private MyData () {};
Provides get instance method public static MyData getinstance () {//Gets the instance object from the current thread-scoped DataSet MyData instance = Threadlocal.get ();
if (instance = = null) {instance = new MyData ();
Threadlocal.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 age) {this.age = age;
}
}
}