本文主要介绍利用java提供的ThreadLocal类去实现线程之间的数据共享。
ThreadLocal内部是一个Map来存放当前线程对象Thread和数据,一个ThreadLocal对象只能存放一个数据,要想存放多个数据,可以创建多个ThreadLocal对象或者将数据打包成一个pojo对象,将pojo对象存放在ThreadLocal中。本文存放pojo对象,用单例的形式实现pojo对象类。
package com.zhangyike.threadLocal;
import java.util.Random;
public class ThreadLocalTest {
public static void main(String[] args) {
//创建两个线程
for (int i = 0; i < 2; i++) {
new Thread(new Runnable(){
@Override
public void run() {
int date = new Random().nextInt();
/*将MyThreadScopeDate对象的name数据保存到当前线程中*/
MyThreadScopeDate.getThreadInstance().setName("name:" + date);
/*将MyThreadScopeDate对象的age数据保存到当前线程中*/
MyThreadScopeDate.getThreadInstance().setAge(date);
System.out.println(Thread.currentThread().getName() + ",has put of date = " + date);
/*从A类中去获取数据*/
new A().get();
/*从B类中去获取数据*/
new B().get();
}
}).start();//开启线程。
}
}
static class A{
public void get(){
//创建与当前线程有关的数据对象,从数据对象中去获取值
MyThreadScopeDate date = MyThreadScopeDate.getThreadInstance();
System.out.println("A from" + Thread.currentThread().getName() + ",has get of date = " + date.getName() + "--" + date.getAge());
}
}
static class B{
public void get(){
//创建与当前线程有关的数据对象,从数据对象中去获取值
MyThreadScopeDate date = MyThreadScopeDate.getThreadInstance();
System.out.println("B from" + Thread.currentThread().getName() + ",has get of date = " + date.getName() + "--" + date.getAge());
}
}
}
/*
ThreadLocal内部是一个map,保存着当前的线程,和该线程保存的对象,所以每次set的时候相当于Map<Thread.current...(),MyThreadScopeDate>,每次取的时候相当于map.get(Thread.current...());
*/
class MyThreadScopeDate{
/*用单例设计模式去创建对象,私有化构造方法,不让创建对象*/
private MyThreadScopeDate(){};
//用ThreadLocal去记录当前线程的MyThreadScopeDate对象。
private static ThreadLocal<MyThreadScopeDate> threadLocal = new ThreadLocal<MyThreadScopeDate>();
//获取对象。
public static MyThreadScopeDate getThreadInstance(){
//得到该线程对应的对象。
MyThreadScopeDate instance = threadLocal.get();
if (instance == null) {
//当前线程没有对应的该对象,则新建一个该对象,并且将该对象保存待ThreadLocal中去
instance = new MyThreadScopeDate();
threadLocal.set(instance);
}
//返回这个对象。
return instance;
}
//一个线程间实现共享的数据。
private String name;
private int age;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}