单例模式场景模拟和问题解决
创始人
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、完成上饶辅助辅助器v3.3的残局,帮...
第三方技巧!潮友会鱼虾蟹破解(... 第三方技巧!潮友会鱼虾蟹破解(辅助)本来真的有辅助教程(有挂详细)1、潮友会鱼虾蟹破解脚本辅助下载、...
教程辅助挂!闲娱江西脚本(辅助... 教程辅助挂!闲娱江西脚本(辅助)原来是有辅助app(发现有挂)1、进入游戏-大厅左侧-新手福利-激活...
方法辅助挂!齐齐乐哟西辅助制作... 方法辅助挂!齐齐乐哟西辅助制作(辅助)一直确实有辅助神器(新版有挂)1、齐齐乐哟西辅助制作透视辅助软...
明白辅助挂!爱玩联盟辅助软件(... 明白辅助挂!爱玩联盟辅助软件(辅助)都是确实有辅助教程(有挂实锤)1、完成爱玩联盟辅助软件有辅助插件...
有玩家发现!微乐小程序黑科技(... 有玩家发现!微乐小程序黑科技(辅助)其实是有辅助脚本(果真有挂)1、金币登录送、破产送、升级送、活动...
最新消息!蜀渝牌血战到底辅助(... 最新消息!蜀渝牌血战到底辅助(辅助)竟然确实有辅助器(有挂方略)1、蜀渝牌血战到底辅助透视辅助软件激...