---
title: "同步synchronized用法"
author: "paynexss"
date: "2016-07-19T16:01:26Z"
tags: ["Synchronized"]
categories: ["编程语言"]
slug: "synchronized"
draft: false
lastmod: "2016-07-19T16:01:26Z"
id: 2312186
url: "https://paynexss.iteye.com/blog/2312186"
---

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

           

[![复制代码](http://common.cnblogs.com/images/copycode.gif)]()

```
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;
    }
}
```