单例设计模式中懒汉式并发访问的安全问题

来源:互联网 发布:网易企业邮箱域名设置 编辑:程序博客网 时间:2024/05/16 02:04

直接看代码吧

//单例设计模式中懒汉式并发访问的安全问题//饿汉式class Sinlge{    private static final Single s = new Single();    private Single(){}    public static Single getInstance()    {        return s;    }}class Single2 {    private static Single2 s;    private Single2(){}    public static Single2 getInstance()    {        //这里为了提高程序性能,因为判断同步锁是比较费时的        if(s==null)//t1 t2 t3 至少从第三个线程开始就不用判断锁了        {            synchronized(Single2.class)            {                if(s==null)                {                    s = new Single2();                }            }        }        return s;    }}class Test implements Runnable{    public void run()    {        Single s = Single.getInstance();    }}class Demo8 {    public static void main(String[] args)     {        Test test = new Test();        Thread t1 = new Thread(test);        Thread t2 = new Thread(test);        t1.start();        t2.start();    }}
0 0
原创粉丝点击