单例模式场景模拟和问题解决
创始人
2025-01-08 14:32:32
0

饿汉式单例

private static Student student = new Student(); 

不存在线程安全问题

懒汉式单例

线程安全问题

package org.example.Singleton;  import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicInteger;  public class SingletonTest {     private static Student student = new Student();      private static Car car = null;      private static AtomicInteger count = new AtomicInteger(0);      private static ExecutorService threadPoolExecutor = Executors.newCachedThreadPool();      private static final CountDownLatch latch = new CountDownLatch(15);      SingletonTest() throws InterruptedException {         threadNonSafeLoad();     }      public static void main(String[] args) throws InterruptedException {         loadInstance();         latch.await();         System.out.println(count.get());     }      private static void threadSafeLoad() {      }      private void threadNonSafeLoad() {         //        System.out.println(this.car);         if (this.car == null) {             count.addAndGet(1);             this.car = new Car();         }         latch.countDown();     }      private static void loadInstance() {         for (int i = 0; i < 15; i++) { //            Thread.sleep(50);             Thread thread = new Thread(() -> {                 try {                     new SingletonTest();                 } catch (InterruptedException e) {                     throw new RuntimeException(e);                 }             });             threadPoolExecutor.execute(thread);         }     } }  class Student {     private String name; }  class Car {     private String name; } 

运行结果:

会多次创建`Car`对象 1~15 

解决方法-双重判断

    private void threadSafeLoad() {         if (this.car == null) {             // 避免每次都加锁进行判断             synchronized (SingletonTest.class) {                 if (this.car == null) {                     count.addAndGet(1);                     this.car = new Car();                 }             }         }         latch.countDown();     } 
    SingletonTest() throws InterruptedException { //        threadNonSafeLoad();         threadSafeLoad();     } 

运行结果:

1 

相关内容

热门资讯

透视普及!微乐小程序黑科技(外... 透视普及!微乐小程序黑科技(外挂),微乐小程序有脚本,教程机巧(有挂攻略)-哔哩哔哩1、每一步都需要...
有了最新消息!微乐小程序黑科技... 有了最新消息!微乐小程序黑科技,微乐陕西小程序辅助(作弊器)窍要教程(本来真的有挂)1)辅助插件:进...
随着!aapoker辅助怎么用... 随着!aapoker辅助怎么用,悦扑克脚本,操作教程(有挂技术)-哔哩哔哩1、进入到aapoker辅...
透视苹果版!微乐小程序黑科技,... 透视苹果版!微乐小程序黑科技,微信小程序微乐破解器(透视)竟然是有挂(有挂详细)-哔哩哔哩1、不需要...
透视揭露!微乐小程序黑科技(外... 透视揭露!微乐小程序黑科技(外挂),微乐多乐跑作弊,教程技法(有挂助手)-哔哩哔哩1、任何透视是真的...
最新消息!微乐小程序免费黑科技... 最新消息!微乐小程序免费黑科技,微信小程序微乐游戏修改器(作弊器)模板教程(都是存在有挂)1、许多玩...
出乎意料的是!玉海楼茶苑怎么开... 出乎意料的是!玉海楼茶苑怎么开挂,新畅游互娱科技,要领教程(竟然有挂)-哔哩哔哩1、起透看视 玉海楼...
透视计算!微乐小程序黑科技,微... 透视计算!微乐小程序黑科技,微乐小程序真的有挂(透视)其实真的有挂(有挂细节)-哔哩哔哩所有人都在同...
透视必备!微乐小程序免费黑科技... 透视必备!微乐小程序免费黑科技(外挂),微乐自建房脚本入口,教程总结(果真有挂)-哔哩哔哩1、打开软...
这一问题亟待解决!微乐小程序免... 这一问题亟待解决!微乐小程序免费黑科技,微乐自建房脚本免费入口(作弊器)步骤教程(原来是真的挂)1、...