同步synchronized用法

今天在高人的指导下,对同步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;
}
}
原文地址:https://www.cnblogs.com/linjiqin/p/2162022.html