多线程单例--双重校验锁


package
caolihua.general; //双重检验锁 public class ObjSingleton { private static ObjSingleton obj; public static ObjSingleton getObj() { //首次判断是否为空 if (obj == null) { try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } //保证只有一个线程进来创建对象 synchronized (ObjSingleton.class) { if (obj == null) { obj = new ObjSingleton(); } } } return obj; } public static void main(String[] args) { Thread t1 = new Thread(new Runnable(){ @Override public void run() { System.out.println(getObj().hashCode()); } },"t1"); Thread t2 = new Thread(new Runnable(){ @Override public void run() { System.out.println(getObj().hashCode()); } },"t2"); Thread t3 = new Thread(new Runnable(){ @Override public void run() { System.out.println(getObj().hashCode()); } },"t3"); t1.start(); t2.start(); t3.start(); } }


可以看到,三个线程创建的都是同一个对象。

posted on 2017-04-23 22:07  老曹123  阅读(240)  评论(0)    收藏  举报

导航