最近碰到一个这样的功能要求:怎么在一个类里面,实现高效并发处理下只可以初始化一次的方法?
实现方式:
1)volatile方式:
[java] view plain copy
- /**
- * 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方式:
[java] view plain copy
- /**
- * 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帮助文档:
时间: 2024-10-25 04:11:17