单例模式

时间:2021-08-26 11:25:32   收藏:0   阅读:26

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();
        }
    }
}

 

原文:https://www.cnblogs.com/liuyang-520/p/15188065.html

评论(0)
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!