zoukankan      html  css  js  c++  java
  • 线程锁的使用

    同步函数的是this,静态同步函数的锁是Class.class,要使同步代码块和静态同步函数都能执行相同的锁,则需要使用Class.class作为锁的对象。

    回顾:

    1.恶汉式:

    Class Single{
        private Single single = new Single();
        public Single(){}
        public static Single getInstance(){
            return single;
        }
    }

    2.懒汉式:

    Class Single{
        private Single single = nullpublic Single(){}
        public static Single getInstance(){
            if(single==null){
                 single = new Single();
            }        
            return single;
        }
    }

    对于恶汉式不会出现安全问题,但是对于懒汉式在多线程访问时会出现安全隐患,所以需要在静态方法上加锁,但是效率是很低的,下面这种双重否定的效率还是可以的,建议使用下面的:

    public static Single getInstance(){
            if(single==null{
                synchronized (Single.class){
                     if(single==null){
                         single = new Single();
                     }
                } 
            }     
            return single;
        }
  • 相关阅读:
    o9.17,习题
    09.17,二维数组,地图
    09.15,一维数组,冒泡排序
    09.11 小兔 成兔问题
    09.01,学习习题
    FTPHelper
    Wpf发送接收 win32消息
    win32Helper
    xml 封装类
    C# 多进程安全
  • 原文地址:https://www.cnblogs.com/dashen/p/4521148.html
Copyright © 2011-2022 走看看