您的位置:首页 > 运维架构

ThreadLocal维护线程局部 变量或线程局部对象

2015-08-25 23:31 302 查看
import java.util.Random;

//线程范围内的共享和作用(ThreadLocal维护线程局部 变量或线程局部对象时,每一个使用他们的线程都是独立的一个副本,不会影响其他 的线程)

public class ThreadLocalTest {

//private static ThreadLocal<Integer> x = new ThreadLocal<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);

//x.set(data);

MyThreadLocalData.getThreadInstance().setName("name" + data);

MyThreadLocalData.getThreadInstance().setAge(data);

new A().get();

new B().get();

}

}).start();

}

}

static class A{

public void get(){

// int data = x.get();

// System.out.println("get "+Thread.currentThread().getName() + " data: " + data);

MyThreadLocalData myData = MyThreadLocalData.getThreadInstance();

System.out.println("A from "+Thread.currentThread().getName() + " getMydata: " + myData.getName() + "," +

myData.getAge());

}

}

static class B{

public void get(){

// int data = x.get();

// System.out.println("get "+Thread.currentThread().getName() + " data: " + data);

MyThreadLocalData myData = MyThreadLocalData.getThreadInstance();

System.out.println("B from "+Thread.currentThread().getName() + " getMydata: " + myData.getName() + "," +

myData.getAge());

}

}

static class MyThreadLocalData{

private MyThreadLocalData(){}

public static /*synchronized*/ MyThreadLocalData getThreadInstance(){

MyThreadLocalData instance = map.get();

if(instance == null){

instance = new MyThreadLocalData();

map.set(instance);

}

return instance;

}

//极寒模式

//private static ThreadLocal<MyThreadLocalData> x = null;

//饱含模式

private static ThreadLocal<MyThreadLocalData> map = new ThreadLocal<MyThreadLocalData>();

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;

}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: