首页 > 编程语言 > 详细

线程:单例懒汉式线程安全

时间:2019-06-12 22:55:03      阅读:144      评论:0      收藏:0      [点我收藏+]
public class Demo1 {
    public static void main(String[] args) {
        Test test = new Test();
        Thread t0 = new Thread(test);
        Thread t1 = new Thread(test);
        t0.start();
        t1.start();
    }
}

class Test implements Runnable{
    public void run() {
        SingleInstance2 singleInstance2 = SingleInstance2.getInstance();
    }
}
//饿汉式,由于公共方法中只有一行公共的代码,所以不会产生线程安全问题
class SingleInstance1{
    private static final SingleInstance1 s = new SingleInstance1();
    private SingleInstance1() {
    }
    public static SingleInstance1 getInstance() {
        return s;
    }
}

//懒汉式,
class SingleInstance2{
    private static  SingleInstance2 s = null;
    private SingleInstance2() {
    }
    public  static SingleInstance2 getInstance() {
        if (s == null) {//尽量减少线程安全代码的判断次数,提高效率
            
            synchronized (SingleInstance2.class) {//使用同步代码块儿实现了线程安全
                if (s == null) {
                    s = new  SingleInstance2();
                }
            }
        }
        return s;
    }
}

 

线程:单例懒汉式线程安全

原文:https://www.cnblogs.com/yumengfei/p/11012690.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!