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


    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;
        }
    }
  • 相关阅读:
    MiniOS系统
    《硅谷传奇》
    《构建之法》1—3章
    学术诚信与职业道德
    Sprint2
    Scrum 项目 7.0 Sprint回顾
    Scrum 项目 6.0 sprint演示
    Scrum 项目 5.0
    Scrum 项目4.0
    操作系统 实验三 进程调度模拟程序
  • 原文地址:https://www.cnblogs.com/yumengfei/p/11012690.html
Copyright © 2020-2023  润新知