1.创建容器类
java
//容器类
public class Contain {
private static final ThreadLocal<DataPackage> local;
static {
local = new ThreadLocal<>();
}
public static ThreadLocal<DataPackage> getLocal() {
return local;
}
}
2.创建数据包类
java
//数据包类
public class DataPackage {
private String str;
private int num;
public static DataPackage getInstance(String str, int num) {
//获取当前线程共享的DataPackage对象
ThreadLocal<DataPackage> local = Contain.getLocal();
DataPackage dataPackage = local.get();
if(dataPackage == null) {
dataPackage = new DataPackage(str, num);
local.set(dataPackage);
}else {
dataPackage.setStr(str);
dataPackage.setNum(num);
}
return dataPackage;
}
private DataPackage(String str, int num) {
super();
this.str = str;
this.num = num;
}
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
@Override
public String toString() {
return "DataPackage [str=" + str + ", num=" + num + "]";
}
}
3.创建A类B类
java
public class A {
public void println() {
//获取容器
ThreadLocal<DataPackage> local = Contain.getLocal();
//通过当前线程获取对应的共享数据
Thread t = Thread.currentThread();
DataPackage data = local.get();
System.out.println(t.getName() + "里的A类对象获取了数据:" + data);
}
}
public class B {
public void println() {
ThreadLocal<DataPackage> local = Contain.getLocal();
Thread t = Thread.currentThread();
DataPackage data = local.get();
System.out.println(t.getName() + "里的B类对象获取了数据:" + data);
}
}
4.创建测试类
java
public class Test01 {
//知识点:线程局部变量共享的问题 -- 使用ThreadLocal解决该需求
public static void main(String[] args) {
//线程1
new Thread(new Runnable() {
@Override
public void run() {
//共享的数据
DataPackage dataPackage = DataPackage.getInstance("我好像在哪见过你", 10);
//获取容器,并存储数据
ThreadLocal<DataPackage> local = Contain.getLocal();
local.set(dataPackage);
//创建对象
A a = new A();
B b = new B();
//获取共享数据
a.println();
b.println();
}
},"线程1").start();
//线程2
new Thread(new Runnable() {
@Override
public void run() {
//共享的数据
DataPackage dataPackage = DataPackage.getInstance("明明就", 20);
//获取容器,并存储数据
ThreadLocal<DataPackage> local = Contain.getLocal();
local.set(dataPackage);
//创建对象
A a = new A();
B b = new B();
//获取共享数据
a.println();
b.println();
}
},"线程2").start();
}
}