java5编程(5)ThreadLocal类及应用技巧 (四)

2014-11-24 07:45:56 · 作者: · 浏览: 3
readScopeDataTwo myData = new MyThreadScopeDataTwo();
myData.setName("name " + data);
myData.setAge(data);
myThreadScopeDataTwo.set(myData);*/

// MyThreadScopeDataTwo.getThreadInstance() 拿到与 本线程相关的实例。
MyThreadScopeDataTwo.getThreadInstance().setName("name " + data);
MyThreadScopeDataTwo.getThreadInstance().setAge(data);

new A().get(); // A 去取数据。
new B().get();
}
}).start();
}
}

static class A{
public void get(){
int data = x.get();
System.out.println("A form " + Thread.currentThread().getName() + " get data :" + data);

MyThreadScopeDataTwo myData = MyThreadScopeDataTwo.getThreadInstance();

System.out.println("A form " + Thread.currentThread().getName() +
" getMyData : " +
myData.getName() + "," + myData.getAge());


}
}

static class B{
public void get(){
int data = x.get();
System.out.println("B form " + Thread.currentThread().getName() + " get data :" + data);

MyThreadScopeDataTwo myData = MyThreadScopeDataTwo.getThreadInstance();

System.out.println("A form " + Thread.currentThread().getName() +
" getMyData : " +
myData.getName() + "," + myData.getAge());
}
}

}

class MyThreadScopeDataTwo {

/*
*

饱汉式。:人家还没有调用我 我就把这个对象创建出来了。
private MyThreadScopeDataTwo(){}
public static MyThreadScopeDataTwo getInstance(){
return instance;
}
private static MyThreadScopeDataTwo instance = new MyThreadScopeDataTwo();


*/

/*

饿汉式:
private MyThreadScopeDataTwo(){}
// 加上 synchronized 时,这个对象就只能创建一个了。
public static synchronized MyThreadScopeDataTwo getInstance(){
if(instance == null){
instance = new MyThreadScopeDataTwo();
}
return instance;
}
private static MyThreadScopeDataTwo instance = null;

*/


private MyThreadScopeDataTwo(){}
public static /*synchronized*/ MyThreadScopeDataTwo getThreadInstance(){
MyThreadScopeDataTwo instance = map.get();
if(instance == null){ // 不用加上 synchronized,两个线程各是各的实例。
instance = new MyThreadScopeDataTwo();
map.set(instance); // 把对象 放进去。。
}
return instance;
}

// 用来专门装对象的。。。
private static ThreadLocal map = new ThreadLocal();

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;
}
}

作者 itm_hadf