java用volatile或AtomicBoolean实现高效并发处理 (只初始化一次的功能要求)
2024-09-02 00:18:43
最近碰到一个这样的功能要求:怎么在一个类里面,实现高效并发处理下只可以初始化一次的方法?
实现方式:
1)volatile方式:
- /**
- * Created by Chengrui on 2015/7/28.
- */
- public class MyThread {
- private static volatile boolean initialized = false;
- public void init(){
- if(initialized == false){
- initialized = true;
- //here is the initialization code
- }
- }
- }
2)AtomicBoolean方式:
- /**
- * Created by Chengrui on 2015/7/28.
- */
- public class MyThread {
- private static AtomicBoolean initialized = new AtomicBoolean(false);
- public void init(){
- if(initialized.compareAndSet(false, true)){
- //here is the initialization code
- }
- }
- }
附:AtomicBoolean帮助文档:
最新文章
- Window.focus()让页面成为当前窗体
- 使用未付费的账号真机调试 iOS 程序,过几天后程序一打开就会闪退
- 批处理命令——call 和 start
- WebForm增删改查
- MVC OF UEditor 图片上传- 额外参数 笔记
- quartz 数据表字典
- 推荐一款开源的原型设计软件--pencil
- Codeforces Round #321 (Div. 2) D. Kefa and Dishes 状压dp
- hadoop命令报错:权限问题
- JS闭包,以及适用场景
- 多重外键关系在java中的处理方案
- Linux Shell 命令--grep
- 敏捷开发的道与术---MPD软件工作坊培训感想(上)
- Laravel 多where组合
- Raft 一致性协议算法 《In search of an Understandable Consensus Algorithm (Extended Version)》
- 【BZOJ1226】学校食堂(动态规划,状态压缩)
- sklearn的train_test_split
- NO2——最短路径
- hbase shell删除键不听使唤
- 分布式计算中WebService的替代方案: RPC (XML-RPC | JSON-RPC)