java 多线程ThreadLocal

阅读更多

import java.util.Random;

/***
 * 线程内独享数据 ,多个线程内操作的数据互不干扰. 
 * ThreadLocal 底层 采用的是 ThreadLocalMap 
 * 自己实现的话就是 可以采用   Map 
 * (个人理解 勿喷)
 */
public class ThreadLocalTest {

	/**
	 * @param args
	 */
	private static ThreadLocal x=new ThreadLocal();
	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);
						x.set(data);
						MyThreadLocalData.getInstance().setName("name"+data);
						MyThreadLocalData.getInstance().setAge(data);
						new A().get();
						new B().get();
					}
				}
			).start();
			
		}
	}

	static class A{
		
		public void get(){
			int data =x.get();
			System.out.println("A from "+Thread.currentThread().getName()+" get Date :"+data);
		}
	}
	
	static class B{
		public void get(){
			int data =x.get();
			MyThreadLocalData mtld=MyThreadLocalData.getInstance();
			System.out.println("B from "+Thread.currentThread().getName()+" get Date :"+mtld.getName()+" --age--"+mtld.getAge());
			System.out.println("B from "+Thread.currentThread().getName()+" get Date :"+data);
		}
	}
}

class MyThreadLocalData{
	private int age;
	private String name;
	private MyThreadLocalData(){} 
	private static ThreadLocal map=new ThreadLocal();
	
	public static MyThreadLocalData getInstance(){
		MyThreadLocalData data=map.get();
		if(data==null){
			data=new MyThreadLocalData();
			map.set(data);
		}
		return data;
	}
	
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	
}

你可能感兴趣的:(多线程ThreadLocal)