您的位置:首页 > 其它

同步synchronized用法

2016-01-19 22:03 459 查看

今天在高人的指导下,对同步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;
}
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: