在多线程下实现懒汉式单例模式是不安全的,所谓的不安全,就是在同一时间段有两个线程同时执行一段代码。解决方法包括将懒汉式改为饿汉式或者让线程同步。下面代码实现线程的同步,保证多线程下的懒汉式单例是安全的。
public class LazyInstance {
public static void main(String[] args) {
Threadlazy t = new Threadlazy("no");
Threadlazy t1 = new Threadlazy("no1");
Threadlazy t2 = new Threadlazy("no2");
Threadlazy t3 = new Threadlazy("no3");
Threadlazy t4 = new Threadlazy("no4");
t.start();
t1.start();
t2.start();
t3.start();
t4.start();
}
}
class Threadlazy extends Thread {
public Threadlazy(String name) {
super(name);
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "创建的对象为"
+ Lazy.getInstance());
}
}
class Lazy {
private static Lazy lazy = null;
public static Lazy getInstance() {
synchronized (Lazy.class) {
if (lazy == null) {
lazy = new Lazy();
}
}
return lazy;
}
}