public class Demo1 { public static void main(String[] args) { Test test = new Test(); Thread t0 = new Thread(test); Thread t1 = new Thread(test); t0.start(); t1.start(); } } class Test implements Runnable{ public void run() { SingleInstance2 singleInstance2 = SingleInstance2.getInstance(); } } //饿汉式,由于公共方法中只有一行公共的代码,所以不会产生线程安全问题 class SingleInstance1{ private static final SingleInstance1 s = new SingleInstance1(); private SingleInstance1() { } public static SingleInstance1 getInstance() { return s; } } //懒汉式, class SingleInstance2{ private static SingleInstance2 s = null; private SingleInstance2() { } public static SingleInstance2 getInstance() { if (s == null) {//尽量减少线程安全代码的判断次数,提高效率 synchronized (SingleInstance2.class) {//使用同步代码块儿实现了线程安全 if (s == null) { s = new SingleInstance2(); } } } return s; } }