Locks In Synchronized Methods
When a thread invokes a synchronized method, it automatically acquires the intrinsic lock for that method's object and releases it when the method returns. The lock release occurs even if the return was caused by an uncaught exception.
注意这句:it automatically acquires the intrinsic lock for that method's object and releases it when the method returns.他锁的是调用该方法的对象
在他锁对象而没有释放锁时,其他线如果要调用该对象的其他同步方法,需要等此方法释放锁后才能调用,
下面看一下例子:
public class Deadlock2 {
static class Friend {
private final String name;
public Friend(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public synchronized void bow() throws InterruptedException {
Thread.currentThread().sleep(500000);
}
public synchronized void hello(){
System.out.println("hello");
}
}
/*
* 不同线程调用同一对象的synchronized方法,要等第一个方法alphonse.bow();释放锁后,才能调用alphonse.hello();
*/
public static void main(String[] args) {
final Friend alphonse =
new Friend("Alphonse");
new Thread(new Runnable() {
public void run() { try {
alphonse.bow();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} }
}).start();
new Thread(new Runnable() {
public void run() {
alphonse.hello();
}
}).start();
}
/*
* 不同线程,调用同一类对象alphonseX,两个对象锁互不影响
*/
/*public static void main(String[] args) {
final Friend alphonse =
new Friend("Alphonse");
final Friend alphonse2 =
new Friend("Alphonse2");
new Thread(new Runnable() {
public void run() { try {
alphonse.bow();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} }
}).start();
new Thread(new Runnable() {
public void run() {
//alphonse.bow();
alphonse2.hello();
}
}).start();
}*/
}