懒加载模式
延迟加载,只有真正使用的时候才会实例化。
package lazysingleton;
public class LazySingLetonTest {
public static void main(String[] args) {
myThread myThread = new myThread();
Thread thread = new Thread(myThread);
thread.start();
myThread myThread1 = new myThread();
Thread thread1 = new Thread(myThread1);
thread1.start();
}
}
class LazySingLeton {
private static LazySingLeton instance;
public LazySingLeton() {
}
public static LazySingLeton getInstance() throws InterruptedException {
if (instance == null)
try {
Thread.sleep(200);
} catch (Exception e) {
e.printStackTrace();
}
{
instance = new LazySingLeton();
}
return instance;
}
}
class myThread extends Thread {
@Override
public void run() {
LazySingLeton lazySingLeton = null;
try {
lazySingLeton = LazySingLeton.getInstance();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(lazySingLeton);
}
}
这样设计时当发生并发时,同时有两个线程进入这个地方,那么也就破坏了只有一个实例的初衷,
所以我们要加锁。。。。。。
加锁位置可以是
在方法前加锁(但是很影响执行效率)
然后我们加锁的位置延迟(此时可能发生两个线程同时进入,第一个线程指令重排后先引用赋值,但是还没有进行初始化,那么第二个线程拿到了一个空指针。)
此时我们应该禁止指令重排
所以在设计时要注意这些地方
1,线程安全
2,优化锁
3,指令重排等问题