ITeye博客

同步synchronized用法

paynexss · 2016-07-19 16:01 · JAVA · 编程语言 · Synchronized · Markdown

今天在高人的指导下,对同步synchronized用法有了更高一层的理解,非常感谢他的无私奉献。在此把代码贴出来方便日后查阅。

           

复制代码

publicclass SfServlet {
    privatestatic ExpressInfoService expressInfoService=null; 
    privatestatic Object lock =new Object();
    
    privatestatic ExpressInfoService getExpressInfoService() {
        if (expressInfoService ==null) {
           //1、用lock把锁的范围缩小,提高效率。
            //2、synchronized (SfServlet.class): 把整个SfServlet类锁住,这样很糟糕并且效率低下。比如调用其他方法,也要等得到锁才能继续做。
synchronized (lock) {
                if (expressInfoService ==null)
                    expressInfoService =new ExpressInfoServiceBean();
            }
        }
        return expressInfoService;
    }
}

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。