ThreadLocal 线程共享多个变量比较优雅的例子

import java.util.Random;
public class ThreadLocalTest {
	public static void main(String[] args){
		for(int i=0;i<2;i++){
		new Thread(new Runnable(){
			@Override
			public void run() {
				int data = new Random().nextInt();
				System.out.println(Thread.currentThread().getName()
						+" has put data:"+data);
				MyThreadScopeData.getThreadInstance().setName("name"+data);
				MyThreadScopeData.getThreadInstance().setAge(data);
				new A().get();
				new B().get();
			}
		}).start();
		}
	}
	static class A {
		public void get(){
			MyThreadScopeData mydate = MyThreadScopeData.getThreadInstance();
			System.out.println("A from "+Thread.currentThread().getName()
					+"get data:"+mydate.getName()+" "+mydate.getAge());
		}
	}
	static class B {
		public void get(){
			MyThreadScopeData mydate = MyThreadScopeData.getThreadInstance();
			System.out.println("B from "+Thread.currentThread().getName()
					+"get data:"+mydate.getName()+" "+mydate.getAge());
		}
	}
}
class MyThreadScopeData{
	private MyThreadScopeData(){}
	private static ThreadLocal map = new ThreadLocal();
	public static MyThreadScopeData getThreadInstance(){
		 MyThreadScopeData instance = map.get();
		if(instance == null){
			instance = new MyThreadScopeData();
			map.set(instance);
		}
		return instance;
	}
	
	private String name;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	private int age;
}

你可能感兴趣的:(java)