synchronized(5)修饰语句块之:synchronized(XXX.class)
2024-08-24 13:55:06
synchronized(XXX.class)有两种写法
synchronized(XXX.class)或者synchronized(obj.getClass())
- Class也是一个类xxx.class和obj.getClass()得到的是Class的一个实例对象.
- 比如String.class是Class类的一个实例,Object.class也是Class的一个实例……。
- 至于XX.class显然是一个Class的实例,而不是一个类。
- synchronized (XXX.class)和synchronized(this)这样的语句在语法上是同一类型的,它们本质上是synchronized(对象),只不过锁的是Class的一个实例xxx.class。
- synchronized(XXX.class)会阻塞后面返回相同class的synchronized(XXX.class)代码.
举例:
public class Thread9 {
private String a = "";
private String b = "";
private String c = ""; private void sync_fun1() throws InterruptedException {
synchronized (a.getClass()) {
int i = ;
while (i-- > ) {
System.out.println(Thread.currentThread().getName() + " : " + i);
try {
Thread.sleep();
} catch (InterruptedException ie) {
}
}
}
} private void sync_fun2() throws InterruptedException {
synchronized (b.getClass()) {
int i = ;
while (i-- > ) {
System.out.println(Thread.currentThread().getName() + " : " + i);
try {
Thread.sleep();
} catch (InterruptedException ie) {
}
}
}
} private synchronized void sync_fun3() {
int i = ;
while (i-- > ) {
System.out.println(Thread.currentThread().getName() + " : " + i);
try {
Thread.sleep();
} catch (InterruptedException ie) {
}
}
} public static void main(String args[]) {
Thread t1 = new Thread(new Runnable() {
public void run() {
try {
new Thread9().sync_fun1();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "t1");
Thread t2 = new Thread(new Runnable() {
public void run() {
try {
new Thread9().sync_fun2();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "t2");
Thread t3 = new Thread(new Runnable() {
public void run() {
new Thread9().sync_fun3();
}
}, "not sync class"); t1.start();
t2.start();
t3.start();
}
}
结果
t1 : 4
not sync class : 4
t1 : 3
not sync class : 3
t1 : 2
not sync class : 2
t1 : 1
not sync class : 1
t1 : 0
not sync class : 0
t2 : 4
t2 : 3
t2 : 2
t2 : 1
t2 : 0
最新文章
- 【转载】PHP PSR-1 基本代码规范(中文版)
- 第一章-第十五题(谈谈你对压力的看法,以及怎么和别人合作, 帮助别人,把压力转化为动力,在互相帮助的环境中成长。)--By林培文
- 从零开始,搭建博客系统MVC5+EF6搭建框架(4)上,前后台页面布局页面实现,介绍使用的UI框架以及JS组件
- java获取两个时间的相隔时间,包括年、月、日、时、分、秒
- C语言程序设计第12次作业
- 【java】:生成excel
- SpringMvc+Mybatis 框架搭建
- LFS 中文版手册发布:如何打造自己的 Linux 发行版
- 成为IT精英,我奋斗了7年
- 编绎OpenJDK
- 页面提交错误,页面间参数传递java.lang.NumberFormatException: null
- Day2 - Python基础2习题集
- Java并发编程--线程池
- 随机x到x之间的值
- knowledge learning things TODO
- siganl tappII的应用及MATLAB调用
- Mycat分片规则详解
- linux kill 掉所有匹配到名字的进程
- Android 浏览器启动应用程序
- Disruptor的伪共享解决方案