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 一個對象.就會出現不同的對象
但有了判空之后