单例模式

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

 

单例模式

上一篇:10Linux服务器编程之:opendir()函数,readdir()函数,rewinddir()函数,telldir()函数和seekdir()函数,closedir()函数


下一篇:在 Windows 下远程桌面连接 Linux - XManager 篇