单例模式

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 static Demo09 getDemo11() {
        if (demo == null) {
            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.getDemo11());
    }

    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();
        }
    }
} 
posted @ 2021-08-26 09:45  牛牛的自留地  阅读(14)  评论(0编辑  收藏  举报