-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathSyncOnObject.java
More file actions
70 lines (68 loc) · 1.45 KB
/
SyncOnObject.java
File metadata and controls
70 lines (68 loc) · 1.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
// lowlevel/SyncOnObject.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// Synchronizing on another object
import java.util.*;
import java.util.stream.*;
import java.util.concurrent.*;
import onjava.Nap;
class DualSynch {
ConcurrentLinkedQueue<String> trace =
new ConcurrentLinkedQueue<>();
public synchronized void f(boolean nap) {
for(int i = 0; i < 5; i++) {
trace.add(String.format("f() " + i));
if(nap) new Nap(0.01);
}
}
private Object syncObject = new Object();
public void g(boolean nap) {
synchronized(syncObject) {
for(int i = 0; i < 5; i++) {
trace.add(String.format("g() " + i));
if(nap) new Nap(0.01);
}
}
}
}
public class SyncOnObject {
static void test(boolean fNap, boolean gNap) {
DualSynch ds = new DualSynch();
List<CompletableFuture<Void>> cfs =
Arrays.stream(new Runnable[] {
() -> ds.f(fNap), () -> ds.g(gNap) })
.map(CompletableFuture::runAsync)
.collect(Collectors.toList());
cfs.forEach(CompletableFuture::join);
ds.trace.forEach(System.out::println);
}
public static void main(String[] args) {
test(true, false);
System.out.println("****");
test(false, true);
}
}
/* Output:
f() 0
g() 0
g() 1
g() 2
g() 3
g() 4
f() 1
f() 2
f() 3
f() 4
****
f() 0
g() 0
f() 1
f() 2
f() 3
f() 4
g() 1
g() 2
g() 3
g() 4
*/