题解 | #创建单例对象#
创建单例对象
https://www.nowcoder.com/practice/9b316cd2d6264776918bc4bc31f37aec
import java.util.Scanner;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
//饿汉式,对象实例化前创建,值一定相同,线程安全
public static volatile Main instance = new Main();
private Main(){
}//private 避免类在外部被实例化
public static Main getInstance(){
return instance;
}
//懒汉式,对象第一次调用时实例化,volatile,和synchonized可确保线程安全
// public static volatile Main instance = null;
// private Main(){
// }
// public static synchronized Main getInstance(){
// if(instance==null){
// instance = new Main();
// }
// return instance;
// }
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
// while (in.hasNextInt()) { // 注意 while 处理多个 case
// int a = in.nextInt();
// int b = in.nextInt();
// System.out.println(a + b);
Main instance1 = getInstance();
Main instance2 = getInstance();
if(instance1.equals(instance2)){
System.out.println("true");
}else{
System.out.println("false");
}
// }
}
}