2015-04-20 15:36:01 -07:00
|
|
|
|
//: concurrency/SyncObject.java
|
2015-05-29 14:18:51 -07:00
|
|
|
|
// <20>2015 MindView LLC: see Copyright.txt
|
2015-04-20 15:36:01 -07:00
|
|
|
|
// Synchronizing on another object.
|
|
|
|
|
import static net.mindview.util.Print.*;
|
|
|
|
|
|
|
|
|
|
class DualSynch {
|
|
|
|
|
private Object syncObject = new Object();
|
|
|
|
|
public synchronized void f() {
|
|
|
|
|
for(int i = 0; i < 5; i++) {
|
|
|
|
|
print("f()");
|
|
|
|
|
Thread.yield();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
public void g() {
|
|
|
|
|
synchronized(syncObject) {
|
|
|
|
|
for(int i = 0; i < 5; i++) {
|
|
|
|
|
print("g()");
|
|
|
|
|
Thread.yield();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public class SyncObject {
|
|
|
|
|
public static void main(String[] args) {
|
|
|
|
|
final DualSynch ds = new DualSynch();
|
|
|
|
|
new Thread() {
|
2015-05-05 11:20:13 -07:00
|
|
|
|
@Override
|
2015-04-20 15:36:01 -07:00
|
|
|
|
public void run() {
|
|
|
|
|
ds.f();
|
|
|
|
|
}
|
|
|
|
|
}.start();
|
|
|
|
|
ds.g();
|
|
|
|
|
}
|
|
|
|
|
} /* Output: (Sample)
|
|
|
|
|
g()
|
|
|
|
|
f()
|
|
|
|
|
g()
|
|
|
|
|
f()
|
|
|
|
|
g()
|
|
|
|
|
f()
|
|
|
|
|
g()
|
|
|
|
|
f()
|
|
|
|
|
g()
|
|
|
|
|
f()
|
|
|
|
|
*///:~
|