慕雪6442864
importjava.util.concurrent.locks.Lock;importjava.util.concurrent.locks.ReentrantLock;publicclassSetting{privatestaticSettingsetting;privatestaticLocklock=newReentrantLock();privateSetting(){}publicstaticSettingget(){if(setting!=null){//tag1returnsetting;}lock.lock();if(setting==null){setting=newSetting();}lock.unlock();returnsetting;}}锁只能保证:访问临界区时的原子性,可见性,有序性.然而在tag1那一行,并不是在临界区中,不受锁的保护,因此即使在双重检查时加锁并初始化,也不能保证其他线程能够看到这个初始化后的单例.因此,需要在单例前面加volatile,保证实例的可见性.