Synchronization

Synchronization(锁)
规则:
类对象和实例对象可以拥有锁,基本类型不能拥有。
锁不能用在域(类有域、函数、内部类.etc),只能用在函数上
volatile 可以用在域上(volatile具有atomicity, visibility, and ordering)
数组:对该数组对象有作用,不能作用与数组内的元素(锁与元素无关)

类对象与实例对象
类对象通常用在静态函数上
eg:
```javva
static synchronized void f(){
    //bussis code
}
```
note: 不要用子类的静态锁对父类静态域进行加锁操作。
The JVM internally obtains and releases the locks for Class objects during class loading and initialization.


实例对象:
有两种方式:代码块 or 函数
```java
void f() { synchronized(this) { /* body */ } }
```
效果等同下面code
```java
synchronized void f() { /* body */ }
```
note:
1.synchronized 不作为函数参数,不被子类继承和重写,interface函数不能使用synchronized。不建议在构造函数使用synchronized。
2.实例对象在父类和子类中,都是同一个锁对象(可重入锁)
eg:
```java
public class Parent {
    private int age;

    public int getAge() {
        synchronized (this){
            System.out.println(this);// result:com.chen.demo.Children@721e0f4f
            return age;
        }
    }

    public void setAge(int age) {
        this.age = age;
    }
}

public class Children extends Parent{
    @Override
    public int getAge() {
        synchronized (this){
            System.out.println(this);// result:com.chen.demo.Children@721e0f4f
            return super.getAge();
        }
    }
}
```
3.内部类,与外部类是不一样的
eg:
```java
public class InnerAndOuter {

    public void getOuterMethod(){
        synchronized (this){
            System.out.println(this);//com.chen.demo.InnerAndOuter@546a03af
        }
    }

    //在外部调用时,需要创建内部类实例对象,在调用对应加锁函数,效果和下面函数类似
    public void getInnerMethod(){
        Inner inner = new Inner();
        inner.getMethod();
    }

    public class Inner {
        public void getMethod(){
            synchronized (this){
                System.out.println(this);//com.chen.demo.InnerAndOuter$Inner@28864e92
            }
        }
    }
}
```
可以通过改变非静态内部类的锁对象实现内外部实例锁对象一致
eg:
```java
public class InnerAndOuter {

    public void getOuterMethod(){
        synchronized (this){
            System.out.println(this);//com.chen.demo.InnerAndOuter@546a03af
        }
    }

    public class Inner {
        public void getMethod(){
            synchronized (InnerAndOuter.this){
                System.out.println(InnerAndOuter.this);//com.chen.demo.InnerAndOuter@546a03af
            }
        }
    }
}
```
锁有获取和释放两个配对操作。
有些显式调用获取锁的,需要显式释放;有些则不用。
 
posted @ 2021-12-05 22:27  !!HelloWorld!!  阅读(494)  评论(0)    收藏  举报