高级并发编程之 线程范围内安全共享数据(使用Map方式)

import java.util.HashMap;
import java.util.Map;
import java.util.Random;



public class ThreadScopeShareData {

	private static int data=0;
	private static Map<Thread,Integer> threadData=new HashMap<Thread,Integer>();//与线程绑定,不同的线程之间的数据相互独立
	public static void main(String[] args) {
		 final A a=new A();
		 final B b=new B();
		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()+"已经放置了数据"+data);
				threadData.put(Thread.currentThread(), data);
				a.get();
				b.get();
			}
			
		}).start();
		}
	}
	static class A{
		public int get(){
		int data=threadData.get(Thread.currentThread());
		System.out.println("A from "+Thread.currentThread().getName()+":"+data);
			return data;
		}
	}
	static class B{
	    public int get(){
	    	int data=threadData.get(Thread.currentThread());
	    	System.out.println("B from "+Thread.currentThread().getName()+":"+data);
	    	return data;
	    }
	}
	
}
运行结果如下:
Thread-0已经放置了数据-144147512
Thread-1已经放置了数据1063579285
A from Thread-0:-144147512
A from Thread-1:1063579285
B from Thread-0:-144147512
B from Thread-1:1063579285

解析:线程范围内安全共享数据

高级并发编程之 线程范围内安全共享数据(使用Map方式)_第1张图片

虽然一直都是对象a在取数据,但是在两个不同的线程内,a.get()方法取到了不同的值,原因就在于map<Thread,Integer>的设计,数据与线程绑定,因此在不同的线程中,取到的数据也不同。


你可能感兴趣的:(高级并发编程之 线程范围内安全共享数据(使用Map方式))