当前位置:网站首页>大白话说说synchronized关键词的三种用法
大白话说说synchronized关键词的三种用法
2022-07-23 05:45:00 【wzf6667】
synchronized关键字的作用域
synchronized关键字的作用域有二种:
某个对象实例内,synchronized aMethod(){}可以防止多个线程同时访问这个对象的synchronized方法(如果一个对象有多个synchronized方法,只要一个线 程访问了其中的一个synchronized方法,其它线程不能同时访问这个对象中任何一个synchronized方法)。这时,不同的对象实例的 synchronized方法是不相干扰的。也就是说,其它线程照样可以同时访问相同类的另一个对象实例中的synchronized方法;
某个类的范围,synchronized static aStaticMethod{}防止多个线程同时访问这个类中的synchronized static 方法。它可以对类的所有对象实例起作用。
通俗来讲,就是可以锁住一个实例对象,拿到实例对象才能运行,另一个是锁住了一个类,相当于锁住了所有的实例对象,防止多个线程同时访问这个类中的synchronized static 方法。
synchronized关键字最主要的三种使用方式:
修饰实例方法: 作用于当前对象实例加锁,进入同步代码前要获得当前对象实例的锁。就像是一个对象的所有方法之间抢夺这个对象的使用权,一旦一个方法抢到了锁,才能运行这个方法。而这个对象的其他synchronized方法这时不能运行。
修饰静态方法: 也就是给当前类加锁,会作用于类的所有对象实例,因为静态成员不属于任何一个实例对象,是类成员( static 表明这是该类的一个静态资源,不管new了多少个对象,只有一份)。所以如果一个线程 A 调用一个实例对象的非静态 synchronized 方法,而线程 B 需要调用这个实例对象所属类的静态 synchronized 方法,是允许的,不会发生互斥现象,因为访问静态 synchronized 方法占用的锁是当前类的锁,而访问非静态 synchronized 方法占用的锁是当前实例对象锁。
修饰代码块: 指定加锁对象,对给定对象加锁,进入同步代码库前要获得给定对象的锁。给定一个锁对象,只有抢到这个锁才能运行。
总结一下
synchronized 关键字加到 static 静态方法和 synchronized(class)代码块上都是是给 Class 类上锁。synchronized 关键字加到实例方法上是给对象实例上锁。尽量不要使用 synchronized(String a) 因为JVM中,字符串常量池具有缓存功能!
边栏推荐
猜你喜欢
随机推荐
匿名上位机v7波形显示
配置TX1的系统 + 设为固态盘启动
使用InfluxDB数据库的疑惑
Interpretation of the paper: develop and verify the deep learning system to classify the etiology of macular hole and predict the anatomical results
二叉树的实现-c
Using one-way linked list to realize queue
Summary of video coding and decoding related data
Uni native plug-in development -- Youmeng one click login
Interpretation of the paper: "i4mc deep: intelligent prediction of N4 methylcytosine sites using deep learning methods with chemical properties"
Question bank of basic principles of steel structure
高电压技术试题及答案
基于对象(Object Based)-两个经典类
视频编解码相关资料汇总
剑指offer 05 两个栈实现队列
Interpretation of the paper: iterative feature representation method to improve the prediction performance of N7 methylguanosine (m7G) sites
理解不能的锁们
[AUTOSAR cantp 1. learn the network layer protocol of UDS diagnosis]
Interpretation of the paper: recognition of enhancer promoter interactions with neural networks based on pre trained DNA vectors and attention mechanisms
APISIX的源码安装与使用
Vs attribute configuration related knowledge


![[AUTOSAR com 3. signal sending and receiving process tx/rx]](/img/f7/e5f89a51cf990ede61ce342e88e5d6.png)






