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)代码.
举例:
1 public class Thread9 { 2 private String a = "123"; 3 private String b = "321"; 4 private String c = "456"; 5 6 private void sync_fun1() throws InterruptedException { 7 synchronized (a.getClass()) { 8 int i = 5; 9 while (i-- > 0) { 10 System.out.println(Thread.currentThread().getName() + " : " + i); 11 try { 12 Thread.sleep(500); 13 } catch (InterruptedException ie) { 14 } 15 } 16 } 17 } 18 19 private void sync_fun2() throws InterruptedException { 20 synchronized (b.getClass()) { 21 int i = 5; 22 while (i-- > 0) { 23 System.out.println(Thread.currentThread().getName() + " : " + i); 24 try { 25 Thread.sleep(500); 26 } catch (InterruptedException ie) { 27 } 28 } 29 } 30 } 31 32 private synchronized void sync_fun3() { 33 int i = 5; 34 while (i-- > 0) { 35 System.out.println(Thread.currentThread().getName() + " : " + i); 36 try { 37 Thread.sleep(500); 38 } catch (InterruptedException ie) { 39 } 40 } 41 } 42 43 public static void main(String args[]) { 44 Thread t1 = new Thread(new Runnable() { 45 public void run() { 46 try { 47 new Thread9().sync_fun1(); 48 } catch (InterruptedException e) { 49 e.printStackTrace(); 50 } 51 } 52 }, "t1"); 53 Thread t2 = new Thread(new Runnable() { 54 public void run() { 55 try { 56 new Thread9().sync_fun2(); 57 } catch (InterruptedException e) { 58 e.printStackTrace(); 59 } 60 } 61 }, "t2"); 62 Thread t3 = new Thread(new Runnable() { 63 public void run() { 64 new Thread9().sync_fun3(); 65 } 66 }, "not sync class"); 67 68 t1.start(); 69 t2.start(); 70 t3.start(); 71 } 72 }
结果
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