代码改变世界

单例模式

2019-02-25 15:23  剑动情缥缈  阅读(139)  评论(0编辑  收藏  举报

1.基本概念

  • 确保一个类只有一个实例

2.恶汉式

  • getInstance()方法调用前,实例已经创建
  • 由于加载类的class文件时必然已经进行初始化,不同线程调用getInstance()方法均会得到唯一对象,为线程安全
  • 代码实现
package com.chengjie;

class Singleton {
    private static Singleton singleton = new Singleton();

    private Singleton() {
    }

    public static Singleton getInstance() {
        return singleton;
    }

    public void service() {
        System.out.println("service() is called!");
    }
}

public class TestSingleton extends Thread {
    @Override
    public void run() {
        System.out.println(Singleton.getInstance().hashCode());
    }

    public static void main(String[] args) {
        TestSingleton[] s = new TestSingleton[10];
        for (int i = 0; i < 10; i++)
            s[i] = new TestSingleton();
        for(TestSingleton t : s)
            t.start();
    }
}
View Code

3.懒汉式

  • getInstance()方法调用前,实例未创建
  • 不同线程调用getInstance()方法时未加锁,为非线程安全
  • 代码实现
package com.chengjie;

class Singleton1 {
    private static Singleton1 singleton = null;

    private Singleton1() {
    }

    public static Singleton1 getInstance() {
        try {
            if (singleton != null) {
                ;
            } else {
                Thread.sleep(3000);
                singleton = new Singleton1();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return singleton;
    }
}

public class TestLazySingleton extends Thread {
    @Override
    public void run() {
        System.out.println(Singleton1.getInstance().hashCode());
    }

    public static void main(String[] args) {
        TestLazySingleton[] s = new TestLazySingleton[10];
        for (int i = 0; i < 10; i++)
            s[i] = new TestLazySingleton();
        for (TestLazySingleton t : s)
            t.start();
    }
}
View Code

4.懒汉式改进-线程安全

  • 对getInstance()加同步关键字
    public static synchronized Singleton1 getInstance() {
        try {
            if (singleton != null) {
                ;
            } else {
                Thread.sleep(3000);
                singleton = new Singleton1();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return singleton;
    }
View Code
  • 同步代码块
    public static  Singleton1 getInstance() {
        try {
            synchronized(Singleton1.class) {
                if (singleton != null) {
                    ;
                } else {
                    Thread.sleep(3000);
                    singleton = new Singleton1();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return singleton;
    }
View Code

5.用途--典型用途

  • 线程池
  • 缓存
  • 日志对象
  • 对话框
  • 打印机
  • 显卡的驱动程序对象

6.参考链接

  https://blog.csdn.net/cselmu9/article/details/51366946