java单例模式

2017-09-21  本文已影响0人  文艺小年青

在java中一共有23种设计模式,
这里学习的是其中的一种:单例设计模式

//饿汉式
class Person {
    //单例可以实现共享数据
    //加static可以是实现对象的生命周期为整个项目运行期间
    static Person person = new Person();
    //不管在哪里调用的都是person对象
    static Person getInstance() {
        return person;
    }
    //我们每次都是通过调用getInstance这个方法来创建对象,我们这个方法会返回person,所以每次都是同一个对象;
}

//懒汉式
class Student {
    //volatile  (为了防止栈的缓存) 每个线程都有自己的栈,他与synchronized构成双层保险,确保唯一性;
    volatile static Student stu = null;
    static Student getInstance() {
        synchronized (Student.class) {
            if (stu == null) {
                stu = new Student();
            }
        }
        return stu;
    }
}
public static void main(String[] args) {
        //Person p = Person.getInstance();
        for (int i = 0; i < 10; i++) {
            new Thread(new Runnable() {
                public void run() {
                    Student student = Student.getInstance();
                    System.out.println(student);
                }
            }).start(); 
        }
    }
上一篇 下一篇

猜你喜欢

热点阅读