欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java 多线程ThreadLocal

程序员文章站 2022-05-28 18:24:03
...

import java.util.Random;

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

	/**
	 * @param args
	 */
	private static ThreadLocal<Integer> x=new ThreadLocal<Integer>();
	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<MyThreadLocalData> map=new ThreadLocal<MyThreadLocalData>();
	
	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