第一种实现方式
/** * 类描述:使用DCL双检查锁机制 */ public class MyObject { private volatile static MyObject myObject; private MyObject(){ } public static MyObject getInstance(){ if (myObject!=null) { }else{ synchronized(MyObject.class){ if (myObject == null) { myObject=new MyObject(); } } } return myObject; } } public class MyThread extends Thread{ @Override public void run(){ System.out.println(MyObject.getInstance().hashCode()); } } public class Run { public static void main(String[] args) { MyThread t1=new MyThread(); MyThread t2=new MyThread(); MyThread t3=new MyThread(); t1.start(); t2.start(); t3.start(); } }第二种实现方式 /** * 使用静态内置类实现单例模式 */ public class MyObject { private static class MyObjectHandler{ private static MyObject myObject=new MyObject(); } private MyObject(){ } public static MyObject getInstance(){ return MyObjectHandler.myObject; } } public class MyThread extends Thread{ @Override public void run(){ System.out.println(MyObject.getInstance().hashCode()); } } public class Run { public static void main(String[] args) { MyThread t1=new MyThread(); MyThread t2=new MyThread(); MyThread t3=new MyThread(); t1.start(); t2.start(); t3.start(); } }第三种实现方式 /** * 使用static代码块实现单例模式 * **/ public class MyObject { private static MyObject instance = null; private MyObject(){ } static{ instance=new MyObject(); } public static MyObject getInstance(){ return instance; } } public class MyThread extends Thread{ @Override public void run(){ System.out.println(MyObject.getInstance().hashCode()); } } public class Run { public static void main(String[] args) { MyThread t1=new MyThread(); MyThread t2=new MyThread(); MyThread t3=new MyThread(); t1.start(); t2.start(); t3.start(); } }