zoukankan      html  css  js  c++  java
  • 单例模式

    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();
            }
        }
    } 
    相识是缘
  • 相关阅读:
    linux中~和/的区别
    Linux centos 7安装
    xshell远程连接虚拟机
    虚拟机Linux不能上网简单有效的解决办法
    visudo
    users
    TreeSizeFree(硬盘文件整理)
    dos2unix
    iconv
    PS1系统变量
  • 原文地址:https://www.cnblogs.com/liuyang-520/p/15188065.html
Copyright © 2011-2022 走看看