线程范围内的数据共享
package Thread;
import java.util.Random;
/**
* 每一个线程都只能得到该线程内的数据
* 类似struts2
* @author LENOVO
*
*/
public class 线程范围内的数据共享2 {
public static void main(String[] args) {
new 线程范围内的数据共享2().begin();
}
public void begin() {
for(int i=0;i<5;i++) {
/**
* 开启5个线程
* 每个线程都有独立的数据
* 每个线程都调用了A,B两个模块
* 使得 线程之间独立,模块之间数据共享
* 同一线程之间调用的模块A的get方法与模块B的get方法使用的是同一个数据
*/
new Thread(new Runnable() {
@Override
public void run() {
int d=new Random().nextInt();
Person p=Person.getThreadinstance();
p.setAge(d);
p.setName("n"+d);
new A().getA();
new B().getB();
}
}).start();
}
}
/**
* 模块A
* @author LENOVO
*
*/
class A{
public void getA() {
Person p=Person.getThreadinstance();
System.out.println(Thread.currentThread().getName()+"模块A:"+p.getName()+","+p.getAge());
}
}
/**
* 模块B
* @author LENOVO
*
*/
class B{
public void getB() {
Person p=Person.getThreadinstance();
System.out.println(Thread.currentThread().getName()+"模块B:"+p.getName()+","+p.getAge());
}
}
}
class Person{
private static ThreadLocal<Person> x=new ThreadLocal<>();
public static Person getThreadinstance() {
Person p=x.get();
if(p==null) {
p=new Person();
x.set(p);
}
return p;
}
private Person() {
}
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;
}
}