ThreadLocal类:
该类提供了线程局部变量,它是一个池 Map<Thread.currentThread,locObj>,
池中为每个线程保存一个独立的局部变量,
每个线程可以从这个池中读取或设置自己的局部变量。
public class ThreadLocalDemo {
//线程局部变量池
//private static ThreadLocal<Object> t = new ThreadLocal<Object>();
private static MyThreadLocal<Object> t=new MyThreadLocal<Object>();
public static Object getValue(){
//System.out.println(Thread.currentThread());
Object obj=t.get();
if(obj==null){
System.out.println("没有....");
Random r=new Random();
obj=r.nextInt(100);
t.set(obj);
}
return obj;
}
}
这里用自己写的一个类当做ThreadLoacal;
package cn.hncu.ThreadLoc;
import java.util.HashMap;
import java.util.Map;
public class MyThreadLocal<T> {
private Map<Thread,Object> map=new HashMap<Thread, Object>();
public Object get(){
Thread curThread =Thread.currentThread();
return map.get(curThread);
}
public Object set(Object obj){
Thread curThread=Thread.currentThread();
return map.put(curThread, obj);
}
}
测试类:
package cn.hncu.ThreadLoc;
public class Hello {
public void aaa(){
Object obj3 = ThreadLocalDemo.getValue();
System.out.println("obj3:"+obj3);
}
public void bbb(){
Object obj5 = ThreadLocalDemo.getValue();
System.out.println("obj5:"+obj5);
}
}
package cn.hncu.ThreadLoc;
import org.junit.Test;
public class ThreadLocTest {
@Test
public void demo1() {
System.out.println(Thread.currentThread());
Object obj1 = ThreadLocalDemo.getValue();
Object obj2 = ThreadLocalDemo.getValue();
System.out.println(obj1 + "," + obj2);
System.out.println(obj1 == obj2);// true
}
@Test
public void demo2() {
// System.out.println(Thread.currentThread());
Object obj1 = ThreadLocalDemo.getValue();
Object obj2 = ThreadLocalDemo.getValue();
System.out.println("obj1:" + obj1);
System.out.println("obj2:" + obj2);
System.out.println(obj1 == obj2); // true
new Hello().aaa();
new Thread() {
/* (non-Javadoc)
* @see java.lang.Thread#run()
*/
@Override
public void run() {
Object obj4 = ThreadLocalDemo.getValue();
System.out.println("obj4:"+obj4);
new Hello().bbb();
}
}.start();
}
}
demo1:
demo2: