线程局部变量共享

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();

	}

}

相关推荐

  1. 线局部变量共享

    2024-07-21 08:08:03       18 阅读
  2. 线局部变量共享 -- 使用ThreadLocal解决该需求

    2024-07-21 08:08:03       15 阅读
  3. python多线和多进程内存共享方式

    2024-07-21 08:08:03       48 阅读
  4. python获取线名称和传递参数,数据共享

    2024-07-21 08:08:03       44 阅读
  5. [Qt学习笔记]Qt线间数据通讯及数据共享

    2024-07-21 08:08:03       33 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-21 08:08:03       52 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-21 08:08:03       54 阅读
  3. 在Django里面运行非项目文件

    2024-07-21 08:08:03       45 阅读
  4. Python语言-面向对象

    2024-07-21 08:08:03       55 阅读

热门阅读

  1. SQL Server报告服务的艺术:在SSRS中打造专业报告

    2024-07-21 08:08:03       17 阅读
  2. 探索Sklearn的分层抽样:数据科学中的精确艺术

    2024-07-21 08:08:03       18 阅读
  3. SQL Server分布式查询:跨数据库的无缝数据探索

    2024-07-21 08:08:03       18 阅读
  4. Vue的渲染函数:深入探索与应用实践

    2024-07-21 08:08:03       16 阅读
  5. mac os 去除压缩包下的__MACOSX

    2024-07-21 08:08:03       17 阅读
  6. Code Effective 学习笔记--第六章可以工作的类

    2024-07-21 08:08:03       15 阅读
  7. 嵌入式编译

    2024-07-21 08:08:03       11 阅读
  8. HTTP请求与响应:Python爬虫技术解析

    2024-07-21 08:08:03       17 阅读