线程内的数据共享
1需求:①线程1的A模块和B模块只能操作属于线程1的相同数据
② 线程2的A模块和B模块只能操作属于线程2的相同数据。
2、实现机制
①使用ThreadLocal实现线程内的数据共享,其实它内部就是一个Map
②通过一个Map<Thread,Object> 来存放与读取对应Thread的数据Object
3、代码
①Map方式:
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
public class ThreadScopeShareData {
//将线程和其数据放入一个Map里面存起来
private static Map<Thread,Integer> threadData=new HashMap<Thread,Integer>();
public static void main(String[] args) {
for(int i=0;i<2;i++){
new Thread(new Runnable(){
@Override
public void run() {
int data=new Random().nextInt();
System.out.println(Thread.currentThread().getName()+" has put data: "+ data);
threadData.put(Thread.currentThread(), data);
new A().get();
new B().get();
}}).start();
}
}
static class A{
public void get(){
int data=threadData.get(Thread.currentThread());
System.out.println("A from"+Thread.currentThread().getName()+" has get data: "+data );
}
}
static class B{
public void get(){
int data=threadData.get(Thread.currentThread());
System.out.println("B from"+Thread.currentThread().getName()+" has get data: "+data );
}
}
}
②使用ThreadLocal类
import java.util.Random;
public class ThreadLocalTest {
//使用ThreadLocal实现线程内的数据共享,其实它内部就是一个Map
private static ThreadLocal<Integer> x=new ThreadLocal<Integer>();
public static void main(String[] args) {
for(int i=0;i<3;i++){
new Thread(new Runnable(){
@Override
public void run() {
int data=new Random().nextInt();
System.out.println(Thread.currentThread().getName()+" has put data: "+ data);
x.set(data);
new A().get();
new B().get();
}}).start();
}
}
static class A{
public void get(){
int data=x.get();
System.out.println("A from"+Thread.currentThread().getName()+" has get data: "+data );
}
}
static class B{
public void get(){
int data=x.get();
System.out.println("B from"+Thread.currentThread().getName()+" has get data: "+data );
}
}
}