单例模式

Singleton

一种创建型模式,某个类采用Singleton模式,则在这个类被创建后,只可能产生一个实例供外部访问,并且提供一个全局的访问点。

 

实现方式1:

public class SingletonClass{

    //内部产生该类唯一的实例,并对外界不可见
    private static final SingletonClass MyInstance = new SingletonClass();

    //私有的构造函数,防止被外界实例化
    private SingletonClass(){
    }

    //返回唯一实例的静态方法,供外界调用
    public static SingletonClass getInstance(){
        return MyInstance;
    }

}

---

实现方式2:

public class SingletonClass2{

    //私有的构造函数,防止被外界实例化
    private SingletonClass2(){
    }

    //静态内部类执行一次,保证线程安全
    private static class InstanceHolder{
        private static final SingletonClass2 MyInstance = new SingletonClass2();
    }

    //返回唯一实例的静态方法,供外界调用
    public static SingletonClass2 getInstance(){
        return InstanceHolder.MyInstance;
    }
}

---

测试类:

class SingletonTest implements Runnable {

    //倒计锁
    private static CountDownLatch latch = new CountDownLatch(1);

    //线程安全的Set
    static Set<String> set = new ConcurrentSkipListSet<String>();

    @Override
    public void run() {
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        set.add(SingletonClass2.getInstance().toString());
    }

    public static void main(String[] args) throws Exception {

        for (int k = 0; k < 2000; k++) {
            SingletonTest tt = new SingletonTest();
            Thread t = new Thread(tt);
            t.start();
        }

        //释放锁
        latch.countDown();

        Thread.sleep(2000);

        System.out.println(set.size());
    }
}

---

输出:

1

2000个线程同时获取实例,Set中只有一个地址,说明只有一个类的实例。

 

end

posted @ 2017-03-12 11:56  dahuandahuan  阅读(121)  评论(0编辑  收藏  举报