1、懒汉模式
package demo; /** * @description: demo09 * @author: liuyang * @create: 2021-08-26 9:23 */ public class Demo09 implements Runnable { private static Demo09 demo = null; private Demo09() {} /** * 同步代码块 * @return */ public static Demo09 getDemo1() { synchronized (Demo09.class) { if (demo == null) { demo = new Demo09(); } } return demo; } /** * 同步方法 * @return */ public synchronized static Demo09 getDemo2() { if (demo == null) { demo = new Demo09(); } return demo; } @Override public void run() { System.out.println(Thread.currentThread().getName() + "---" + Demo09.getDemo2()); } public static void main(String[] args) { Demo09 demo = new Demo09(); for (int i = 0; i < 100; i++) { Thread t = new Thread(demo); t.setName("t" + i); t.start(); } } }