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

相关内容

热门资讯

透视插件!hhpoker万能辅... 透视插件!hhpoker万能辅助器,智星菠萝可以辅助吗,技术分享(有挂规律)智星菠萝可以辅助吗辅助器...
wpk辅助工具下载!hhpko... wpk辅助工具下载!hhpkoer辅助器(透视)一贯存在有挂(教你教程)1、起透看视 hhpkoer...
透视美元局!aapoker辅助... 透视美元局!aapoker辅助包,wpk透视脚本,大神讲解(有挂详情);aapoker辅助包软件透明...
透视规律!aapoker透视插... 透视规律!aapoker透视插件下载,wepoker透视,推荐几款新版(有挂技巧)(1)透视规律!a...
德普之星app安卓版破解版!w... 德普之星app安卓版破解版!wpk私人局有透视吗(透视)竟然有挂(第三方教程)1、这是跨平台的德普之...
透视有挂!wpk有没有脚本,智... 透视有挂!wpk有没有脚本,智星菠萝辅助怎么买,安装教程(有挂规律);一、智星菠萝辅助怎么买软件透明...
透视存在!hhpoker透视脚... 1、透视存在!hhpoker透视脚本安卓,智星德州菠萝透视插件工具,免费测试版(有挂黑科技);该软件...
aapoker辅助工具存在吗!... aapoker辅助工具存在吗!wepoker作弊视频(透视)一贯是真的有挂(2025新版教程)1、金...
透视辅助!aapoker辅助器... 透视辅助!aapoker辅助器是真的吗,智星德州有脚本吗,黑科技教程(有挂技巧)进入游戏-大厅左侧-...
透视透视!wpk辅助器安装,德... 透视透视!wpk辅助器安装,德普之星辅助器,科技分享(有挂黑科技)是一款可以让一直输的玩家,快速成为...