多线程-单例模式
程序员文章站
2022-07-12 20:35:16
...
单例模式
一、概念
饿汉模式、懒汉模式
二、示例
package com.study.current.thread.day02; /** * 单例,多线程 */ public class InnerSingleton { private static class Singletion{ private static Singletion single = new Singletion(); } public static Singletion getInstance(){ return Singletion.single; } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub } }
package com.study.current.thread.day02; import java.util.DuplicateFormatFlagsException; public class DoubleCheckDemo { private static DoubleCheckDemo dc ; public static DoubleCheckDemo getDc(){ if(dc == null){ try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (DoubleCheckDemo.class) { if(dc == null){ dc = new DoubleCheckDemo(); } } } return dc ; } /** * @param args */ public static void main(String[] args) { Thread t1 = new Thread(new Runnable() { public void run() { System.out.println(DoubleCheckDemo.getDc().hashCode()); } }); Thread t2 = new Thread(new Runnable() { public void run() { System.out.println(DoubleCheckDemo.getDc().hashCode()); } }); t1.start(); t2.start(); } }