饿汉式线程不安全及调试问题
代码
这里我们新建一个懒汉式单例:
public class LazySingleton {
//私有构造方法
private static LazySingleton instance;
private LazySingleton() {};
public static LazySingleton getInstance() {
if (instance == null) {
instance = new LazySingleton();
}
return instance;
}
}
线程类:
public class ExectorThread implements Runnable {
public void run() {
LazySingleton instance = LazySingleton.getInstance();
System.out.println(Thread.currentThread().getName() + ":" + instance);
}
}
测试类:
import thread.ExectorThread;
public class LazySingletonTest {
public static void main(String[] args) {
Thread thread1 = new Thread(new ExectorThread());
Thread thread2 = new Thread(new ExectorThread()