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

相关内容

热门资讯

9分钟德州局!hhpoker到... 9分钟德州局!hhpoker到底可以作弊吗,hhpkoer辅助器,详细教程(有挂软件);1、起透看视...
七分钟插件辅助!wpk私人局有... 七分钟插件辅助!wpk私人局有透视吗,wpk辅助器是真的吗,详细教程(有挂插件);1、首先打开wpk...
十分钟规律!wepoker可以... 十分钟规律!wepoker可以透视码,wepoker私人局怎么玩,详细教程(有挂下载)软件透明挂微扑...
7分钟辅助器!aapoker能... 7分钟辅助器!aapoker能控制牌吗(透视脚本)详细辅助安装(真是有挂);1、不需要AI权限,帮助...
7分钟正品!hhpoker辅助... 7分钟正品!hhpoker辅助软件下载,hhpoker软件可以玩吗,详细教程(有挂软件)1、hhpo...
1分钟透视辅助!wpk辅助软件... 1分钟透视辅助!wpk辅助软件,wpk有那种辅助吗,详细教程(有挂胜率)1、该软件可以轻松地帮助玩家...
5分钟看底牌!wepoker线... 5分钟看底牌!wepoker线上大神(透视底牌)详细辅助透视(竟然真的有挂)1)wepoker线上大...
二分钟软件安装包!hh pok... 二分钟软件安装包!hh poker辅助有用吗(透视脚本)详细辅助安装(一直是真的有挂)是一种具有地方...
六分钟开辅助器!aapoker... 六分钟开辅助器!aapoker透视怎么用(透视脚本)详细辅助程序(一贯有挂)辅助器中分为三种模型:软...
六分钟辅助!wepoker有没... 六分钟辅助!wepoker有没有给,wepoker辅助器免费,详细教程(有挂方法);该软件可以轻松地...