对于静态方法而言,使用当前类本身充当锁package threadPage;class Singleton { private Singleton() { } private static Singleton instance = null; public static Singleton getInstance() { if (instance == null) { synchronized (Singleton.class) { if (instance == null) { instance = new Singleton(); } } } return instance; }}public class TestSingleton { public static void main(String[] args) { Singleton s1 = Singleton.getInstance(); Singleton s2 = Singleton.getInstance(); System.out.println(s1 == s2); }}
单例模式懒汉Java_JAVA_单例模式懒汉式的线程安全问题
最新推荐文章于 2024-07-10 12:43:46 发布