單例模式 懶漢式 為什么要兩次判空


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 一個對象.就會出現不同的對象

 

 但有了判空之后

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM