1.如何创建线程同步即安全的单例模式?
package season16; //线程同步即安全的创建单例模式 public class TestThread { public static void main(String[] args) { new Thread(new Runnable() { @Override public void run() { System.out.println(Singleton.getInstance()); } }).start(); new Thread(new Runnable() { @Override public void run() { System.out.println(Singleton.getInstance()); } }).start(); } } class Singleton { private static Singleton instance; //单例:饿汉模式 private Singleton(){ System.out.println("Singleton.Singleton()"); } //单例:懒汉模式 public synchronized static Singleton getInstance(){ if(instance==null){ try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } instance=new Singleton(); } return instance; } }