线程特有存储模式(Thread Specific Storage)
来源:互联网 发布:淘宝上整点抢商品技巧 编辑:程序博客网 时间:2024/06/04 18:54
八、线程特有存储模式(Thread Specific Storage)
1、核心思想
通过不共享变量实现了线程安全,避免了与锁的消耗及相关的问题。每个线程都有且只持有一个变量实例
2、适用场景
a、需要使用非线程安全对象,但又不希望引入锁。
b、使用线程安全对象,但希望避免其使用的锁的开销和相关问题。
c、隐式参数传递:他是线程全局可见的
d、特定于线程的单例模式,希望每个线程有且仅有该类的一个实例。
3、线程池环境下使用该模式
同一个线程可能处理多个任务,此时需要考虑在适当的时间和地方清理线程特有对象。
/** * 线程上下文全局变量 * @author huzhiqiang * */public class ThreadContent { private static ThreadLocal<String> threadLocal = new ThreadLocal<String>(); public static String getThreadLocal() { return threadLocal.get(); } public static void setThreadLocal(String value) { ThreadContent.threadLocal.set(value); }}public class ThreadSpecificSecureRandom { //该类的唯一实例 public static final ThreadSpecificSecureRandom INSTANCE = new ThreadSpecificSecureRandom(); private static final ThreadLocal<SecureRandom> secureRandom = new ThreadLocal<SecureRandom>(){ //初始化返回对象 protected SecureRandom initialValue() { SecureRandom srnd; try { srnd = SecureRandom.getInstance("SHA1PRNG"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); srnd = new SecureRandom(); } return srnd; } }; private ThreadSpecificSecureRandom(){ } public int nextInt(int upperBound){ SecureRandom srnd = secureRandom.get(); return srnd.nextInt(upperBound); } public void setSeed(long seed){ SecureRandom s = secureRandom.get(); s.setSeed(seed); }}
0 0
- 线程特有存储模式(Thread Specific Storage)
- 多线程设计模式——Thread Specific Storage(线程特有存储)模式
- Thread-Specific Storage 模式
- 线程局部存储 Thread Local Storage 线程特定数据 Thread-Specific Data
- Thread-Specific Storage
- Thread-Specific Storage
- Thread Specific Storage
- Thread-Specific Storage Pattern
- 第十一章 Thread-Specific Storage
- 线程局部存储Thread Local Storage(TLS)
- 线程本地存储(Thread Local Storage TLS)
- TLS(thread - local storage)线程局部存储
- 线程局部存储(Thread Local Storage,TLS)
- TLS(Thread Local Storage)线程本地存储
- 线程专有数据(Thread-Specific Data)
- Thread-Specific Data(线程私有数据)
- 线程本地存储(Thread Local Storage, TLS)
- 线程局部存储 Thread Local Storage
- 10、C++计算两个矩阵的乘积
- lede 增加新固件型号
- 【Java基础】Java数据类型
- NTC33 Classic Spin-and-win Ugga Bugga slot
- python装饰器、with和contextmanager
- 线程特有存储模式(Thread Specific Storage)
- 爬虫学习记录(二)
- 如果不想弄了,厌烦了
- UVa 10815 Andy's First Dictionary 【STL】【set】
- 性能优化之快速响应的用户界面
- [指数型生成函数] HDU 1521 排列组合
- 说说什么是回调
- linux下运用c实现队列调度
- 西蒙斯告诉你何为传奇人生 James Simons