单例模式_demo

参考:(15条消息) 单例模式Demo_zixing08的博客-CSDN博客

单例模式详细解析 - 知乎 (zhihu.com)

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 }

执行结果

 

posted @ 2023-06-24 12:18  hemeiwolong  阅读(2)  评论(0编辑  收藏  举报