P494
同步控制块必须指定一个对象才能进行同步,通常,最合理的对象就是在其上调用方法的当前对象: synchronized(this),在PairManager2中采用了这种方法。这样,当为同步控制块请求锁的时候,对象的其它同步控制方法就不能被调用了。所以其效
果不过是缩小了同步控制的范围。
但是随后就给了一段代码:
//: c13:SyncObject.java
// Synchronizing on another object
// From 'Thinking in Java, 3rd ed. ' (c) Bruce Eckel 2002
// www.BruceEckel.com. See copyright notice in CopyRight.txt.
import com.bruceeckel.simpletest.*;
class DualSynch {
private Object syncObject = new Object();
public synchronized void f() {
System.out.println( "Inside f() ");
// Doesn 't release lock:
try {
Thread.sleep(500);
} catch(InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println( "Leaving f() ");
}
public void g() {
synchronized(syncObject) {
System.out.println( "Inside g() ");
try {
Thread.sleep(500);
} catch(InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println( "Leaving g() ");
}
}
}
public class SyncObject {
private static Test monitor = new Test();
public static void main(String[] args) {
final DualSynch ds = new DualSynch();
new Thread() {
public void run() {
ds.f();
}
}.start();
ds.g();
monitor.expect(new String[] {
"Inside g() ",
"Inside f() ",
"Leaving g() ",
"Leaving f() "
}, Test.WAIT + Test.IGNORE_ORDER);
}
} ///:~
这里两种同步方法都用到了 但结果并不是 "这样,当为同步控制块请求锁的时候,对象的其它同步控制方法就不能被调用了 "
第一段文字针对的是下面的代码:
//: c13:CriticalSection.java
// Synchronizing blocks instead of entire methods. Also
// demonstrates protection of a non-thread-safe class