• 单例模式


    单线程下可用

    class Singleton {
        private static Singleton singleton;
        private Singleton(){
            System.out.println("***************new Singleton***************");
        }
        public static Singleton getInstance() {
            if (singleton == null) {
                singleton = new Singleton();
            }
            return singleton;
        }
    
        public void print() {
            System.out.println("Hello Singleton***************");
        }
        @Override
        public String toString() {
            return Singleton.class.getName();
        }
    }
    class  App {
        public static void main(String[] args) {
            Singleton instance = Singleton.getInstance();
            instance.print();
        }
    }
    

    多线程下(推荐)

    class Singleton2 {
        private static volatile Singleton2 singleton;
        private Singleton2(){
            System.out.println("***************new Singleton2***************");
        }
        public static Singleton2 getInstance() {
            if (singleton == null) {
                synchronized (Singleton2.class) {
                    if (singleton == null) {
                        singleton = new Singleton2();
                    }
                }
            }
            return singleton;
        }
    
        public void print() {
            System.out.println("Hello Singleton2***************");
        }
        @Override
        public String toString() {
            return Singleton2.class.getName();
        }
    }
    
    class  App2 {
        public static void main(String[] args) {
            for (int i = 0; i < 5; i++) {
                new Thread(() -> Singleton2.getInstance().print(), "thread-" + i).start();
            }
        }
    }
    
    
  • 相关阅读:
    cookie和session详解
    MacOS Sierra10.12.4编译Android7.1.1源代码必须跳的坑
    LeetCode——4Sum &amp; 总结
    C#深拷贝
    iOS9中怎样注冊远程通知
    hdu1542 Atlantis (线段树+扫描线+离散化)
    HTML杂记
    OpenCV中图像算术操作与逻辑操作
    java集群优化——ORM框架查询优化原理
    RVM切换ruby版本号
  • 原文地址:https://www.cnblogs.com/bjxly/p/13731948.html
Copyright © 2020-2023  润新知