ThreadLocal的使用方法
ThreadLocal的含义是Thread Local Variable,它可以声明一个字段,使得不同的线程访问这个字段时,获取的都是不同的副本,互不影响。
import java.util.ArrayList; import java.util.List; import java.util.Random;public class ThreadLocalTest { public static void main(String[] args) { Judge.prepare(); new Player(1).start(); new Player(2).start(); new Player(3).start(); } }class Judge { public static int MAX_VALUE = 10; private static int targetValue; public static void prepare() { Random random = new Random(); targetValue = random.nextInt(MAX_VALUE) + 1; } public static boolean judge(int value) { return value == targetValue; } }class Player extends Thread { private int playerId; public Player(int playerId) { this.playerId = playerId; } @Override public void run() { boolean success = false; while(!success) { int value = Attempt.guess(Judge.MAX_VALUE); success = Judge.judge(value); System.out.println(String.format("Plyaer %s Attempts %s and %s", playerId, value, success ? " Success" : "Failed")); } Attempt.review(String.format("[IFNO] Plyaer %s Completed by ", playerId)); } }class Attempt { private static ThreadLocal<Record> history = new ThreadLocal<Record>(); public static int guess(int maxValue) { Record record = getRecord(); Random random = new Random(); int value = 0; do { value = random.nextInt(maxValue) + 1; } while (record.contains(value)); record.save(value); return value; } public static void review(String info) { System.out.println(info + getRecord()); } private static Record getRecord() { Record record = history.get(); if(record == null) { record = new Record(); history.set(record); } return record; } }class Record { private List<Integer> attemptList = new ArrayList<Integer>();; public void save(int value) { attemptList.add(value); } public boolean contains(int value) { return attemptList.contains(value); } @Override public String toString() { StringBuffer buffer = new StringBuffer(); buffer.append(attemptList.size() + " Times: "); int count = 1; for(Integer attempt : attemptList) { buffer.append(attempt); if(count < attemptList.size()) { buffer.append(", "); count++; } } return buffer.toString(); } }
Plyaer 2 Attempts 8 and Failed Plyaer 3 Attempts 6 and Failed Plyaer 1 Attempts 5 and Failed Plyaer 2 Attempts 7 and Success Plyaer 3 Attempts 9 and Failed Plyaer 1 Attempts 9 and Failed Plyaer 3 Attempts 2 and Failed Plyaer 1 Attempts 2 and Failed [IFNO] Plyaer 2 Completed by 2 Times: 8, 7 Plyaer 3 Attempts 4 and Failed Plyaer 1 Attempts 1 and Failed Plyaer 3 Attempts 5 and Failed Plyaer 1 Attempts 3 and Failed Plyaer 3 Attempts 1 and Failed Plyaer 1 Attempts 10 and Failed Plyaer 3 Attempts 8 and Failed Plyaer 1 Attempts 6 and Failed Plyaer 3 Attempts 7 and Success Plyaer 1 Attempts 4 and Failed [IFNO] Plyaer 3 Completed by 8 Times: 6, 9, 2, 4, 5, 1, 8, 7 Plyaer 1 Attempts 7 and Success [IFNO] Plyaer 1 Completed by 9 Times: 5, 9, 2, 1, 3, 10, 6, 4, 7
public class ThreadLocal<T> { ... public T get() { Thread t = Thread.currentThread(); ThreadLocalMap map = getMap(t); if (map != null) { ThreadLocalMap.Entry e = map.getEntry(this); if (e != null) return (T)e.value; } return setInitialValue(); } ThreadLocalMap getMap(Thread t) { return t.threadLocals; } ...}
ThreadLocal的使用方法相关推荐
- ThreadLocal的重要方法介绍
ThreadLocal主要方法 protected T initialValue():初始化 该方法会返回当前线程对应的"初始值",这是一个延迟加载的方法,只有在调用get的时候才 ...
- threadlocal的set()方法中的内存回收
ThreadLocal在执行set()方法的时候,实际执行set()逻辑的是其内部类ThreadLocalMap. private void set(ThreadLocal<?> key, ...
- 全方位,多角度理解ThreadLocal
欢迎关注方志朋的博客,回复"666"获面试宝典 来源:https://blog.csdn.net/zzg1229059735/article/details/82715741 本次 ...
- 为何每次用完 ThreadLocal 都要调用 remove()
点击上方蓝色"方志朋",选择"设为星标"回复"666"获取独家整理的学习资料! 什么是内存泄漏 Key 的泄漏 Value 的泄漏 如何避免 ...
- 这玩意比ThreadLocal叼多了,吓得我赶紧分享出来。
点击上方蓝色"方志朋",选择"设为星标" 回复"666"获取独家整理的学习资料! Dubbo的一次提交开始 故事得从前段时间翻阅 Dubbo ...
- 优雅的使用 ThreadLocal
前言 在我们日常 Web 开发中难免遇到需要把一个参数层层的传递到最内层,然后中间层根本不需要使用这个参数,或者是仅仅在特定的工具类中使用,这样我们完全没有必要在每一个方法里面都传递这样一个 通用的参 ...
- Java并发编程:线程封闭和ThreadLocal详解
什么是线程封闭 当访问共享变量时,往往需要加锁来保证数据同步.一种避免使用同步的方式就是不共享数据.如果仅在单线程中访问数据,就不需要同步了.这种技术称为线程封闭.在Java语言中,提供了一些类库和机 ...
- 深入浅出ThreadLocal,你会吗?
ThreadLocal全面解析 学习目标 了解ThreadLocal的介绍 掌握ThreadLocal的运用场景 了解ThreadLocal的内部结构 了解ThreadLocal的核心方法源码 了解T ...
- ThreadLocal的正确使用与原理
ThreadLocal是什么 ThreadLocal是线程Thread中属性threadLocals即ThreadLocal.ThreadLocalMap的管理者,ThreadLocal用于给每个线程 ...
最新文章
- 海思3536:PC客户端编译过程报错及解决方法
- 武汉大专计算机专业分数线,武汉高考分数线最低的大专,2021年武汉大专最低分数线是多少...
- Delphi面向对象编程的20条规则
- android分析windowManager、window、viewGroup之间关系
- django项目学习之QQ登录
- ubuntu 安装 TensorFlow、opencv3 的 tips
- mui 头部tab代码
- 【直通顶会 ICCV2021比赛大揭秘】ICCV2021比赛信息汇总
- angular中如何定义全局变量_如何在Angular 2 / Typescript中声明全局变量?
- JPA基础(四):第一个JPA实例与JPA主键生成策略
- u-boot移植随笔:System.map文件格式
- 计算机的组成 —— 主板
- AUTOCAD——添加自定义填充图案
- python建模的步骤_python基础教程之Python 建模步骤|python基础教程|python入门|python教程...
- 【论文笔记】(FGSM公式推导)Explaining and Harnessing Adversarial Examples
- 永远不要使用 Boolean 对象
- 利用backtrace和ucontex定位segment错误【转】
- 硬盘数据恢复原理与方法(一)
- 正方教务系统成绩爬虫的实现
- Tomcat单机多实例配置
热门文章
- String、StringBuffer与StringBuilder之间区别 (转载)
- \\s+ split替换
- android学习笔记之十服务(Service)
- 【OSX】build AOSP 2.3.7时的build error解决
- 求1 + 2 + 3...+ n的和
- .NET工程师必须掌握的知识点
- [转载]ESFramework 4.0 快速上手(15) -- 客户端登录验证
- linux下如何查看某个软件 是否安装??? 安装路径在哪???
- Python_赋值和深浅copy
- github上fork了别人的项目后,再同步更新别人的提交