/** * @author JHX * @date 2018/12/1 13:58 */public class SingleClass { private static SingleClass singleClass = null; public static SingleClass getSingleClass() { if (singleClass == null) { synchronized (SingleClass.class) { if (singleClass == null) { singleClass = new SingleClass(); } } } return singleClass; }}复制代码
这是双重锁单例的模式,然后写一个测试类
/** * @author JHX * @date 2018/12/1 14:00 */public class CoountDownLatchTest { public static void main(String[] args) { final CountDownLatch countDownLatch = new CountDownLatch(1); ExecutorService exce = new ThreadPoolExecutor(15, 15, 20, TimeUnit.SECONDS, new ArrayBlockingQueue(20)); for (int i = 0; i < 15; i++) { final int num = i; Thread thread = new Thread(new Runnable() { @Override public void run() { System.out.println("第" + num + "开始"); try { countDownLatch.await(); System.out.println(SingleClass.getSingleClass().toString()); } catch (InterruptedException e) { e.printStackTrace(); } } }); exce.execute(thread); } try { Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); } countDownLatch.countDown(); System.out.println("main end"); exce.shutdown(); }}复制代码
上述测试结果发现,很小概率的打印出来的地址不一样
singleClass = new SingleClass();复制代码
singleClass 类对象的 引用存在栈上
new SingleClass()在堆上开辟内存
指针指向堆上的内存
上述就是出现问题的原因