单例模式
懒汉式解决线程安全问题
class Singleton{ private Singleton() {//私有化构造器 } private static volatile Singleton s = null; public static Singleton getInstance() { if(s==null) {//第一个线程进去后,已经创建了实例,其他线程不需要再去握住这个锁了 synchronized (Singleton.class) { if (s == null) { s = new Singleton(); } } } return s; } } public class TestSingleton { public static void main(String[] args) { Singleton s1 = Singleton.getInstance(); Singleton s2 = Singleton.getInstance(); } }