线程安全问题

来源:互联网 发布:成都瑞星数据恢复 编辑:程序博客网 时间:2024/06/09 21:49
public class ClientGenerator {
   private static volidate Hello helloClient = null;

   public static Hello getHelloClient() {
       if (helloClient == null) { // a
           synchronized (ClientGenerator.class) {
               if (helloClient == null) {  
                   helloClient = new Hello();  
                   helloClient.init();   // b               
               }
           }
       }
       return helloClient;
   }
}


这段代码的问题还有一个,刚找到的。 因为我有一句 hello.init(); 也就是说如果线程1 执行到语句 b, 但是没有执行完, 当线程2 过来的时候 执行到a,立即退出。然后线程2会用到Hello类的方法(因为语句b没执行完,Hello里有些属性没有初始化),返回的helloClient就是不完整的,如果线程2用到helloClient的属性的时候,因为线程一还没初始化完,会存在线程安全问题


方案:

加个临时变量,完成动作。 在赋值给volatile

Hello tmp = new Hello();tmp.init(); helloClient = tmp;

线程安全的三个必要条件 原子性  可见性 有序性


么么哒,好开心


原创粉丝点击