import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; /** * 单例模式之懒汉模式 * 懒汉模式之高效模式 * DLC双判断模式 */ public class SingleClassLazySync { private static SingleClassLazySync singleClassLazySync; private SingleClassLazySync() { } public static SingleClassLazySync getInstance() { if (singleClassLazySync == null) { synchronized (SingleClassLazySync.class) { if (singleClassLazySync == null) { System.out.println("i m in new instance!"); singleClassLazySync = new SingleClassLazySync(); } } } return singleClassLazySync; } static class A implements Runnable { @Override public void run() { System.out.println(SingleClassLazySync.getInstance().hashCode()); } } public static void main(String[] args) { ThreadPoolExecutor executor = new ThreadPoolExecutor(5, 5, 0l, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); boolean flag = true; for (int i = 0; i < 5; i++) executor.execute(new A()); executor.shutdown(); } }
两个判断的位置
第一个为了日后获取实例的线程准备
第二个为了刚刚获得锁的线程准备,如果没有这个,将会有同步问题。
输出结果:
原文地址:https://www.cnblogs.com/qfxydtk/p/8728937.html
时间: 2024-10-08 19:07:30