根据多个实例字段的状态,在需要锁定时哪种方法更好?

时间:2015-08-12 10:50:59

标签: java synchronization locking

我有一个类,必须初始化指向四个不同模板的四个实例变量。此初始化在方法内部完成,该方法可以由多个线程同时访问。同步用于控制线程进入初始化代码块的方式。代码如,

private void initializeTemplates(){
    if(template1 == null){
          synchronized(this){
             if(template1 ==  null)//initialize template
          }
    }
    if(template2 == null){
          synchronized(this){
             if(template1 ==  null)//initialize template
          }
    }
    //similar if blocks for the other two templates
}

这段代码对我来说似乎很难看。我想知道我是否可以使用或运算符,as,

private void initializeTemplates(){
    if(template1 == null || template2 == null || template3 ==null || template4 == null){
          synchronized(this){
             if(template1 ==  null)//initialize template
             if(template2 ==  null)//initialize template
             if(template3 ==  null)//initialize template
             if(template5 ==  null)//initialize template
          }
    }
}

第二种方法有问题吗?对我来说似乎很好。

0 个答案:

没有答案