话不多说,先看代码:
package com.example.test;
public class Test192 {
public static void main(String[] args) {
Test192 test = new Test192();
inner i =test.new inner();
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
i.show2();
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
test.show(i);
}
});
t1.start();
t2.start();
}
public void show(inner innerclass) {
synchronized(innerclass) {
for(int i = 0;i<10;i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
class inner{
public synchronized void show2() {
for(int i =0;i<5;i++) {
System.out.println(i);
}
}
}
}
看show1锁住的是inner类的对象,也就是实际传入的inner对象,而show2是synchronized修饰的方法,锁住的是当前调用该方法的对象,两者是统一对象,所以呈现的是同步执行。