package Test; public class ThreadAndSingleton { private ThreadAndSingleton() { } private static ThreadAndSingleton threadAndSingleton = null; /** * 试试不加synchronized关键字,会出现两个实例的 * @param sleepTime * @return */ public static synchronized ThreadAndSingleton getIntstance(int sleepTime) { if (threadAndSingleton == null) { try { Thread.sleep(sleepTime); } catch (InterruptedException e) { e.printStackTrace(); } threadAndSingleton = new ThreadAndSingleton(); } return threadAndSingleton; } public static void main(String[] args) { /** * 下面这就属于模型驱动模式 */ Thread th1 = new Thread(new Runnable() { @Override public void run() { System.out.println("th1:" + ThreadAndSingleton.getIntstance(1000)); } }); Thread th2 = new Thread(new Runnable() { @Override public void run() { System.out.println("th2:" + ThreadAndSingleton.getIntstance(0)); } }); th1.start(); th2.start(); } }
关于
getIntstance方法被同步的说明:如果不同步,同事访问这个方法可能造成进入后等待,然后另一次访问开始了,结果造成两个实例,就不是单例模式了。