package Thread;
import java.util.Random;
import java.util.concurrent.TimeUnit;
/**
* ThreadLocal示例
*/
public class ThreadLocalTest {
public static void main(String[] args) {
for(int i=0; i<10; i++){
new Thread(){
public void run() {
Person.getInstance().setAge(new Random().nextInt(100));
try {
TimeUnit.SECONDS.sleep(new Random().nextInt(4));
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() +"---get---"+
Person.getInstance().getAge());
};
}.start();
}
Person.clear();
}
}
class Person{
private static ThreadLocal<Person> threadLocal = new ThreadLocal<Person>();
private int age;
//关键代码
public static Person getInstance(){
Person person = threadLocal.get();//
每个线程对应一个实例
if(person ==null){
person = new Person();
threadLocal.set(person);
}
return person;
}
public static void clear(){
threadLocal.remove();
}
public int getAge() {
return age;
}
public void setAge(int age) {
System.out.println(Thread.currentThread().getName() +"----set----"+ age);
this.age = age;
}
}