Java高并发编程:线程范围内共享数据

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/woshimuyi1025/article/details/80578518

所谓线程范围内共享数据,即对于相同的程序代码,多个模块在同一个线程中运行时要共享一份数据,而在另外线程中运行时又共享另外一份数据,API中为我们提供了一个操作线程范围内共享数据的类ThreadLocal,对于线程范围内共享数据的应用,在ThreadLocal的应用场景中进行了介绍,然后主要对它的使用进行讲解,演示了由单一数据的共享到将多个数据封装到一个对象中,然后进行共享。在开始先用一个Map集合简单实现线程范围内数据的共享

1. 使用Map实现线程范围内数据的共享

原理:将线程对象作为map的键存入,这样就保证了map对象的唯一,也就保证了线程内数据的唯一

关键: 明确一点,把当前线程对象作为map集合的键存进去

package com.yql.Thread;

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

public class ThreadScopeShareData {

	//private static int data = 0;//这段代码没用,所有的值都是在map中操作的,每次重新定义了data
	private static Map<Thread, Integer> threadData = new HashMap<Thread, 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);
					threadData.put(Thread.currentThread(), data);
					new A().get();
					new B().get();
				}
			}).start();
		}
	}
	
	static class A{
		public void get(){
			int data = threadData.get(Thread.currentThread());
			System.out.println("A from " + Thread.currentThread().getName() 
					+ " get data :" + data);
		}
	}
	
	static class B{
		public void get(){
			int data = threadData.get(Thread.currentThread());			
			System.out.println("B from " + Thread.currentThread().getName() 
					+ " get data :" + data);
		}		
	}
}

打印结果:

Thread-0 has put data :68393323
Thread-1 has put data :2109971011
A from Thread-0 get data :68393323
A from Thread-1 get data :2109971011
B from Thread-1 get data :2109971011
B from Thread-0 get data :68393323

猜你喜欢

转载自blog.csdn.net/woshimuyi1025/article/details/80578518
今日推荐