zoukankan      html  css  js  c++  java
  • singleton

    package singleton;

    public class Singleton1 {
    //私有化构造方法
    private Singleton1() {
    System.out.println("this is a singleton pattern");
    }

    //通过自身创建一个实例对象
    private static Singleton1 instance = new Singleton1();

    //获取此对象的方法
    public static Singleton1 getinstance() {
    return instance;
    }
    }
    懒汉式:会造成多线程不安全的问题
    package singleton;

    //懒汉式
    public class Singleton2 {
    private static Singleton2 instance;

    private Singleton2() {
    }

    ;

    public static Singleton2 getInstance() {
    if (instance == null) {
    try {
    Thread.sleep(10);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    instance = new Singleton2();
    }
    return instance;
    }
    }
    package singleton;

    public class Main {
    public static void main(String[] args) {
    for (int i=0;i<100;i++){
    new Thread(()->
    System.out.println(Singleton2.getInstance().hashCode())
    ).start();
    }
    }
    }
    双重检查
    package singleton;

    //双重检查
    public class Singleton3 {
    private static Singleton3 instance;

    private Singleton3() {
    }

    ;

    public static Singleton3 getInstance() {
    //判断是否为空
    if (instance == null) {
    synchronized (Singleton3.class) {

    if (instance == null) {
    try {
    Thread.sleep(10);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    instance = new Singleton3();
    }
    }
    }
    return instance;
    }
    }
    package singleton;

    public class Main {
    public static void main(String[] args) {
    for (int i = 0; i < 100; i++) {
    new Thread(() -> System.out.println(Singleton3.getInstance().hashCode())).start();
    }
    }
    }


    另外一种方式:

    package singleton;

    public class Singleton4 {
    private Singleton4(){};
    private static class instanceGet{
    private static final Singleton4 instance = new Singleton4();
    }
    public static Singleton4 getInstance(){
    return instanceGet.instance;
    }
    }

    最后的枚举单例:
    枚举没有构造方法
    package singleton;

    public enum Singleton5 {
    INSTANCE;
    public static void main(String[] args) {
    for (int i = 0; i < 100; i++) {
    new Thread(() -> System.out.println(Singleton5.INSTANCE.hashCode())).start();
    }
    }
    }
  • 相关阅读:
    计算相邻字段 四至
    eclipse+terminal
    10 行 Python 代码实现模糊查询/智能提示
    Sublime Text 3,有了Anaconda就会如虎添翼
    Visual Studio上开发Python六大功能
    11 Python Libraries You Might Not Know
    linux安装PyCharm,PyCharm常用快捷键及调试模式,pycharm里面对文件夹或者文件进行重命名
    mysql mac客户端: sequel,mysql-workbench
    ImageMagick convert多张照片JPG转成pdf格式,pdfunite合并PDF文件
    互联网金融ABS为何遭遇急刹车?
  • 原文地址:https://www.cnblogs.com/zrmj/p/11445613.html
Copyright © 2011-2022 走看看