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

    

最新文章

  1. 【转载】PHP PSR-1 基本代码规范(中文版)
  2. 第一章-第十五题(谈谈你对压力的看法,以及怎么和别人合作, 帮助别人,把压力转化为动力,在互相帮助的环境中成长。)--By林培文
  3. 从零开始,搭建博客系统MVC5+EF6搭建框架(4)上,前后台页面布局页面实现,介绍使用的UI框架以及JS组件
  4. java获取两个时间的相隔时间,包括年、月、日、时、分、秒
  5. C语言程序设计第12次作业
  6. 【java】:生成excel
  7. SpringMvc+Mybatis 框架搭建
  8. LFS 中文版手册发布:如何打造自己的 Linux 发行版
  9. 成为IT精英,我奋斗了7年
  10. 编绎OpenJDK
  11. 页面提交错误,页面间参数传递java.lang.NumberFormatException: null
  12. Day2 - Python基础2习题集
  13. Java并发编程--线程池
  14. 随机x到x之间的值
  15. knowledge learning things TODO
  16. siganl tappII的应用及MATLAB调用
  17. Mycat分片规则详解
  18. linux kill 掉所有匹配到名字的进程
  19. Android 浏览器启动应用程序
  20. Disruptor的伪共享解决方案

热门文章

  1. [Rust] Setup Rust for WebAssembly
  2. UIButton的图片和文字相对位置调整
  3. android动画具体解释四 创建动画
  4. 让Linq的OrderBy支持动态字段
  5. iOS开发——高级篇——线程保活
  6. YTU 2555: 老大的烦恼
  7. 计算机学院大学生程序设计竞赛(2015’11)1005 ACM组队安排
  8. html5--项目实战-仿天猫(移动端页面)
  9. I.MX6 wpa_cli 使用
  10. BZOJ4561:圆的异或并(扫描线+set||splay||线段树)