单例设计模式中懒汉式并发访问的安全问题

    xiaoxiao2026-09-13  3

    直接看代码吧

    //单例设计模式中懒汉式并发访问的安全问题 //饿汉式 class Sinlge { private static final Single s = new Single(); private Single(){} public static Single getInstance() { return s; } } class Single2 { private static Single2 s; private Single2(){} public static Single2 getInstance() { //这里为了提高程序性能,因为判断同步锁是比较费时的 if(s==null)//t1 t2 t3 至少从第三个线程开始就不用判断锁了 { synchronized(Single2.class) { if(s==null) { s = new Single2(); } } } return s; } } class Test implements Runnable { public void run() { Single s = Single.getInstance(); } } class Demo8 { public static void main(String[] args) { Test test = new Test(); Thread t1 = new Thread(test); Thread t2 = new Thread(test); t1.start(); t2.start(); } }
    转载请注明原文地址: https://ju.6miu.com/read-1312029.html
    最新回复(0)