单例模式场景模拟和问题解决
创始人
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 

相关内容

热门资讯

透视代打!wpk有机器人吗(w... 透视代打!wpk有机器人吗(wPK)最新ai辅助黑科技(智能ai辅助)(2026已更新)-哔哩哔哩进...
第6分钟辅助!德州之星辅助软件... 第6分钟辅助!德州之星辅助软件介绍(德州之星)外挂辅助神器软件(AI辅助)(2024已更新)-哔哩哔...
透视私人局!aapoker到底... 透视私人局!aapoker到底有挂吗(AAPOkER)外挂辅助工具ai(发牌机制)(2023已更新)...
透视软件!wpk外挂是真的还是... 透视软件!wpk外挂是真的还是(wPK)最新ai辅助黑科技(智能ai辅助)(2023已更新)-哔哩哔...
第3分钟辅助!德州之星辅助器多... 第3分钟辅助!德州之星辅助器多少钱(德州之星)外挂辅助神器软件(AI辅助)(2022已更新)-哔哩哔...
透视工具!aapoker外挂教... 透视工具!aapoker外挂教程(aapoKer)外挂辅助工具ai(发牌机制)(2026已更新)-哔...
辅助透视!wpk代理合作(WP... 辅助透视!wpk代理合作(WPK)最新ai辅助黑科技(智能ai辅助)(2021已更新)-哔哩哔哩1....
第一分钟辅助!德州ai辅助有用... 第一分钟辅助!德州ai辅助有用(德州)外挂辅助神器软件(AI辅助)(2023已更新)-哔哩哔哩1、德...
透视挂!aapoker辅助工具... 透视挂!aapoker辅助工具存在吗(aapoker)外挂辅助工具ai(发牌机制)(2025已更新)...
透视存在!wpk德州伙牌打法(... 透视存在!wpk德州伙牌打法(wpK)最新ai辅助黑科技(智能ai辅助)(2020已更新)-哔哩哔哩...