• 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();
    }
    }
    }
  • 相关阅读:
    web集群和分布式服务以及消息补偿机制几种方案
    什么是幂等性
    Dubbo面试常见问题
    mysql 缓存机制
    mysql面试题
    在IDEA中用Gradle构建项目时使用lombok以依赖出现出错
    jdbcType与javaType的对应关系
    通用Mapper的使用
    Java各种对象(PO,BO,VO,DTO,POJO,DAO,Entity,JavaBean,JavaBeans)的区分
    dubbo面试题
  • 原文地址:https://www.cnblogs.com/zrmj/p/11445613.html
Copyright © 2020-2023  润新知