Bootstrap

线程局部变量共享

1.创建容器类

import java.util.concurrent.ConcurrentHashMap;

//容器类
public class Contain {

	private static final ConcurrentHashMap<Thread, Integer> map;
	
	 static {
		 map = new ConcurrentHashMap<>();
	 }

	public static ConcurrentHashMap<Thread, Integer> getMap() {
		return map;
	}
	 
}

2.创建A类来操作共享的数据

import java.util.concurrent.ConcurrentHashMap;

public class A {
	
	public void println() {
		
		//获取容器
		ConcurrentHashMap<Thread, Integer> map = Contain.getMap();
		
		//通过当前线程获取对应的共享数据
		Thread t = Thread.currentThread();
		Integer data = map.get(t);
		System.out.println(t.getName() + "里的A类对象获取了数据:" + data);
		
	}

}

3.创建测试类

import java.util.concurrent.ConcurrentHashMap;

public class Test01 {

	//知识点:线程局部变量共享的问题 -- 共享单个数据
	public static void main(String[] args) {

		//线程1
		new Thread(new Runnable() {

			@Override
			public void run() {
				//共享的数据
				int num = 10;

				//获取容器,并存储数据
				ConcurrentHashMap<Thread, Integer> map = Contain.getMap();
				map.put(Thread.currentThread(), num);

				//创建对象
				A a = new A();

				//获取共享数据
				a.println();

			}
		},"线程1").start();

		//线程2
		new Thread(new Runnable() {

			@Override
			public void run() {
				//共享的数据
				int num = 20;

				//获取容器,并存储数据
				ConcurrentHashMap<Thread, Integer> map = Contain.getMap();
				map.put(Thread.currentThread(), num);

				//创建对象
				A a = new A();

				//获取共享数据
				a.println();
				
			}
		},"线程2").start();

	}

}

;