单例模式 懒汉式 为什么要两次判空
class User { public static int i; public static int j; private static User user = null; public User() {} public static User getInstance() { if(user == null) { try { Thread.sleep(1); } catch (InterruptedException e) { } synchronized (User.class) { i++; if(user == null) { user = new User(); j++; return user; } } } return user; } private String name; private int age; }
public static void main(String[] args) { int i = 10; ExecutorService executorService = Executors.newFixedThreadPool(10); do { executorService.execute(()-> { User u = User.getInstance(); System.out.println(System.identityHashCode(u)); }); i--; } while (i >0); try { Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(User.getInstance().i + " " + User.getInstance().j); }
如果不判空的话,会出现多个线程在等待获取当前的锁,当其中的一个线程释放掉锁后,又会重新new 一个对象.就会出现不同的对象
但有了判空之后