Synchronization
2021/12/5 23:20:56
本文主要是介绍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 } } } } ``` 锁有获取和释放两个配对操作。 有些显式调用获取锁的,需要显式释放;有些则不用。
这篇关于Synchronization的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-09-28pyqt 怎么打包整个项目-icode9专业技术文章分享
- 2024-09-28laravel Commands 创建带有参数的 Artisan 命令的步骤和示例-icode9专业技术文章分享
- 2024-09-28antd怎么实现渲染tiff图片-icode9专业技术文章分享
- 2024-09-28英文半角中划线和中文全角的中划线有什么区别-icode9专业技术文章分享
- 2024-09-28nvm npm 和node 他们之间有什么关系-icode9专业技术文章分享
- 2024-09-28Node Version Manager (nvm)使用教程-icode9专业技术文章分享
- 2024-09-28nvm命令太慢,是什么原因-icode9专业技术文章分享
- 2024-09-28Kotlin 如何增加、删除和修改 MutableStateFlow 中的值。-icode9专业技术文章分享
- 2024-09-28Kotlin的stateFlow.update 写法介绍-icode9专业技术文章分享
- 2024-09-28kotlin 怎么获取当前时间格式-icode9专业技术文章分享