饿汉单例模式 优点没有加任何锁执行效率高。绝对的线程安全 缺点类加载时就已经存在了占用内存空间
懒汉单例模式 简单懒汉 加锁 利用内部类实现懒汉模式利用内部类只有在外部类被加载时内部类才被加载
发令枪
CountDownLatch
package com.gupao.demo.single.serialize;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import java.util.concurrent.CountDownLatch;import com.gupao.demo.single.lazy.LazyTwo;public class App {public static void main(String[] args) throws IOException, ClassNotFoundException {//// Hungry instance Hungry.getInstance();// // FileOutputStream filenew FileOutputStream("o.obj");// ObjectOutputStream outOnew ObjectOutputStream(file);// outO.writeObject(instance);// // ObjectInputStream innew ObjectInputStream(new FileInputStream("o.obj"));// Hungry instance2 (Hungry) in.readObject();// // System.out.println(instanceinstance2);int count200;//发令枪CountDownLatch downnew CountDownLatch(count);for(int i0;i< count;i){new Thread(new Runnable() {Overridepublic void run() {try {//发令枪阻塞down.await();} catch (Exception e) {e.printStackTrace();}LazyTwo instance LazyTwo.getInstance();System.out.println(System.currentTimeMillis()":"instance);}}).start();//发令枪计数 count--down.countDown();}}}