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用于给每个线程 ...
最新文章
- matlab消去前一个图,各位matlab高手,如何从2个3元方程中消去一个变量,然后做3维图形~...
- 【django】类视图
- java gui 控制台_在GUI面板中创建Java控制台
- python二维元素向量_详解python Numpy中求向量和矩阵的范数
- matlab多种分配方案_基于MATLAB的水资源优化分配问题动态规划解法
- openwrt 19 overlay 空间不足_【邯郸】2020年度市级科技企业孵化器和众创空间拟认定名单公示...
- GuaiGuai ---- 1
- Merkle Patricia Tree (MPT) 以太坊merkle技术分析
- git远程仓库中master及其余分支间代码的合并
- python 解决for读取文件出现的换行符
- Centos7 Kubernetes(k8s) 开发服务器(单服务器)部署 sentinel 哨兵熔断限流断路器
- 工具使用-----Jmeter-脚本的录制
- Linux0.11内核--进程调度分析之1.初始化
- 麦本本从u盘启动计算机,麦本本怎么设计u盘启动顺序
- webpack的学习
- [转][darkbaby]任天堂传——失落的泰坦王朝(上)
- 关于amd cpu超频 个人心得
- 用photoshop做电影胶片效果
- 2.11del和pop的区别
- nodeJS 中文API node.js 中文文档