syncobject.java
来自「java编程思想的源码,11-16,和上次上传的1-10的源码是一块的,希望大家」· Java 代码 · 共 50 行
JAVA
50 行
//: 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);
}
} ///:~
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?