threadlocal的基本实现

package com.cgm.threadlocal;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

public class MyThread {
static Map<Thread, Object> map=new HashMap<Thread, Object>();
public static Object getObj(){
Thread  th=Thread.currentThread();
Object o=map.get(th); 
if (o==null) {               
o=new Random().nextInt(1000);
map.put(th, o);  //保证每一个线程都是一个单独的值 互不干预
}
return o;
}

}



测试类

package com.cgm.threadlocal;

import org.junit.Test;

public class ThreadLoaclTest {
@Test
public void testThread(){


     Object o1= MyThread.getObj();
     Object o2= MyThread.getObj();
  System.out.println(o1);
  System.out.println(o2);  //o1 o2 同一个值
 
 
Thread t=new Thread(){
public void run() {
     Object o3= MyThread.getObj();
     Object o4= MyThread.getObj();
  System.out.println(o3);
  System.out.println(o4);  //o3 o4 同一个值

}
};



}




}

你可能感兴趣的:(threadLocal)