单例模式_demo
参考:(15条消息) 单例模式Demo_zixing08的博客-CSDN博客
Singleton.java
1 package com.hmb; 2 3 public class Singleton { 4 private static class MySingleton { 5 private static Singleton singleton = new Singleton(); 6 } 7 8 public static Singleton getInstance() { 9 return MySingleton.singleton; 10 } 11 }
Main.java
1 package com.hmb; 2 3 import com.hmb.Singleton; 4 5 public class Main { 6 public static void main(String[] args) { 7 for (int i = 0; i < 100; i++) { 8 new Thread(() -> { 9 System.out.println(Thread.currentThread().getName() + " " + Singleton.getInstance().hashCode()); 10 }).start(); 11 } 12 } 13 }
执行结果