<p>
</p>
<p>
<img alt="" src="http://my.csdn.net/uploads/201204/13/1334288858_1539.png" />
</p>
<p>
</p>
<p>
</p>
<p>
package cn.itcast.heima2;<br />
import java.util.Random;<br />
public class ThreadLocalTest {<br />
private static ThreadLocal<Integer> x = new ThreadLocal<Integer>();<br />
private static ThreadLocal<MyThreadScopeData> myThreadScopeData = new ThreadLocal<MyThreadScopeData>();<br />
public static void main(String[] args) {<br />
for(int i=0;i<2;i++){<br />
new Thread(new Runnable(){<br />
@Override<br />
public void run() {<br />
int data = new Random().nextInt();<br />
System.out.println(Thread.currentThread().getName() <br />
+ " has put data :" + data);<br />
x.set(data);<br />
/* MyThreadScopeData myData = new MyThreadScopeData();<br />
myData.setName("name" + data);<br />
myData.setAge(data);<br />
myThreadScopeData.set(myData);*/<br />
MyThreadScopeData.getThreadInstance().setName("name" + data);<br />
MyThreadScopeData.getThreadInstance().setAge(data);<br />
new A().get();<br />
new B().get();<br />
}<br />
}).start();<br />
}<br />
}<br />
static class A{<br />
public void get(){<br />
int data = x.get();<br />
System.out.println("A from " + Thread.currentThread().getName() <br />
+ " get data :" + data);<br />
/* MyThreadScopeData myData = myThreadScopeData.get();;<br />
System.out.println("A from " + Thread.currentThread().getName() <br />
+ " getMyData: " + myData.getName() + "," +<br />
myData.getAge());*/<br />
MyThreadScopeData myData = MyThreadScopeData.getThreadInstance();<br />
System.out.println("A from " + Thread.currentThread().getName() <br />
+ " getMyData: " + myData.getName() + "," +<br />
myData.getAge());<br />
}<br />
}<br />
static class B{<br />
public void get(){<br />
int data = x.get(); <br />
System.out.println("B from " + Thread.currentThread().getName() <br />
+ " get data :" + data);<br />
MyThreadScopeData myData = MyThreadScopeData.getThreadInstance();<br />
System.out.println("B from " + Thread.currentThread().getName() <br />
+ " getMyData: " + myData.getName() + "," +<br />
myData.getAge()); <br />
} <br />
}<br />
}<br />
class MyThreadScopeData{<br />
private MyThreadScopeData(){}<br />
public static /*synchronized*/ MyThreadScopeData getThreadInstance(){<br />
MyThreadScopeData instance = map.get();<br />
if(instance == null){<br />
instance = new MyThreadScopeData();<br />
map.set(instance);<br />
}<br />
return instance;<br />
}<br />
//private static MyThreadScopeData instance = null;//new MyThreadScopeData();<br />
private static ThreadLocal<MyThreadScopeData> map = new ThreadLocal<MyThreadScopeData>();<br />
<br />
private String name;<br />
private int age;<br />
public String getName() {<br />
return name;<br />
}<br />
public void setName(String name) {<br />
this.name = name;<br />
}<br />
public int getAge() {<br />
return age;<br />
}<br />
public void setAge(int age) {<br />
this.age = age;<br />
}<br />
}<br />
</p> |
|