Java: Singleton mode in a multithreaded environment

1. The previous code:

public class Singleton_01 {
    
    
	
	//声明静态变量
	private static Singleton_01 s;
	
	//构造方法私有化,外部不能创建对象
	private Singleton_01(){
    
    
		
	}
	
	//在获取对象时,先判断对象是否被实例化
	//如果对象还没有被创建,就创建
	//如果已经被实例化,则直接返回对象
	public static Singleton_01 getInstance(){
    
    
		if(s == null){
    
    
			s = new Singleton_01();
		}
		
		return s;
	}
	
}

In a multithreaded environment, the above code will not work. Because of the concurrency and parallelism in the multithreaded environment, different threads may execute this method at the same time, resulting in the creation of multiple objects.
Insert picture description here
2. Code improvement:

public class Singleton_01 {
    
    
	//静态变量,存储创建的对象
	private static Singleton_01 s;
	//私有化构造方法,外部不能随意创建对象
	private Singleton_01() {
    
    

	}
	//对外提供一个获取对象的方式
	public  static Singleton_01 getInstance() {
    
    
		if (s == null) {
    
    
			synchronized (Singleton_01.class) {
    
    
				if (s == null) {
    
    
					s = new Singleton_01();
				}
			}
		}
		return s;
	}
}

In this case, only the first request needs to be queued. Even if there are many threads executing this method at the same time, they will not be queued because the method is not locked, and multiple threads can come in to execute the method at the same time. In addition, s has already been assigned in the first request, so when it is judged that s==null, it is also false, and the value of s is directly obtained.

Guess you like

Origin blog.csdn.net/qq_41504815/article/details/113483063