1.饿汉式
public class ThreadPoolManager { private ThreadPoolManager() { } private static ThreadPoolManager threadPoolManager = new ThreadPoolManager(); public static ThreadPoolManager getInstance() { return threadPoolManager; } }
2.懒汉式
public class ThreadPoolManager { private ThreadPoolManager() { } private static volatile ThreadPoolManager threadPoolManager; public static ThreadPoolManager getInstance() { if (threadPoolManager == null) { synchronized (ThreadPoolManager.class) { if (threadPoolManager == null) { threadPoolManager = new ThreadPoolManager(); } } } return threadPoolManager; } }
3.两者相比较而言,讲究性能和节省资源选择懒汉式,如果是平时开发而且这种单例类较少,我建议用饿汉式,因为饿汉式较为简单而且线程安全,一个类的实例也不会占用多少资源。