Java——》synchronized的使用
推荐链接:
总结——》【Java】
总结——》【Mysql】
总结——》【Redis】
总结——》【Kafka】
总结——》【Spring】
总结——》【SpringBoot】
总结——》【MyBatis、MyBatis-Plus】
总结——》【Linux】
总结——》【MongoDB】
总结——》【Elasticsearch】
Java——》synchronized的使用
synchronized是
互斥锁
,锁是基于对象
实现的,每个线程基于synchronized绑定的对象去获取锁!
有明确指定锁对象:
- synchronized(变量名):当前变量做为锁
- synchroinzed(this):this做为锁
无明确指定锁对象
:同步方法
和同步代码块
- 有static修饰:当前
类.class
做为锁(类锁
) - 无static修饰:当前
对象
做为锁(对象锁
)
public class MiTest {public static void main(String[] args) {// 锁的是当前Test.classTest.a();Test test = new Test();// 锁的是new出来的test对象test.b();}}class Test{public static synchronized void a(){System.out.println("1111");}public synchronized void b(){System.out.println("2222");}
}