Java_线程_ThreadLocal

本博文为子墨原创,转载请注明出处!
http://blog.csdn.net/zimo2013/article/details/8952721
public class Test{
	private static ThreadLocal<Person> localPerson = new ThreadLocal<Person>();//实际上是Map集合,隐含本线程Key和与之对应的值Value
	public static void main(String[] args){
		for(int i=0; i<10; i++){
			new Thread(new Runnable(){
				public void run(){
					int data = new Random().nextInt(200);
					Person p = Person.getInstance();
					p.set(data+"", data);
					
					new A().get();
					new B().get();
				}
			}).start();
		}
	}
	static class A{
		public void get(){
			Person p = localPerson.get();//得到与本线程有关联的对象,map中get(key)
			p.showInstance();
		}
	}
	static class B{
		public void get(){
			Person p = localPerson.get();
			p.showInstance();
		}
	}
public class Person
{
	private String name;
	private int age;
	private Person(){}
	private static ThreadLocal<Person> local = new ThreadLocal<Person>();//类部是一个Map
	public static Person getInstance(){
		/*从这个函数,应该明白,一个线程只有一个实例对象,多个线程可以对应多个不同的实例对象,
		该对象,只在本线程中有效!!! 很好方法~~~*/
		Person p = local.get();	//local为ThreadLocal的实现,通过get方法,可以获取与当前正在执行的线程有关的对象,即Person的实现对象
		if(p == null){			//类部隐藏了很多实现细节
			p = new Person();
			local.set(p);		//向local中添加元素p,其中还有隐含一个当前线程信息,所有在执行get方法时,能获得与之对应的信息;
		}
		return p;
	}
	public static void showInstance(){
		Person p = local.get();
		if( p == null){
			p = getInstance();
		}
		System.out.println(Thread.currentThread().getName()+": Name:" +p.name+ " Age:"+p.age);
	}
	
	public void set(String name, int age) {
		this.name = name;
		this.age = age;
	}

}

你可能感兴趣的:(ThreadLoal)