-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathExplicitCriticalSection.java
More file actions
45 lines (39 loc) · 960 Bytes
/
ExplicitCriticalSection.java
File metadata and controls
45 lines (39 loc) · 960 Bytes
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
package thinkinginjava.concurrency;
// Using explicit Lock objects to create critical sections.
import java.util.concurrent.locks.*;
// Synchronize the entire method:
class ExplicitPairManager1 extends PairManager {
private Lock lock = new ReentrantLock();
public synchronized void increment() {
lock.lock();
try {
p.incrementX();
p.incrementY();
store(getPair());
} finally {
lock.unlock();
}
}
}
// Use a critical section:
class ExplicitPairManager2 extends PairManager {
private Lock lock = new ReentrantLock();
public void increment() {
Pair temp;
lock.lock();
try {
p.incrementX();
p.incrementY();
temp = getPair();
} finally {
lock.unlock();
}
store(temp);
}
}
public class ExplicitCriticalSection {
public static void main(String[] args) throws Exception {
PairManager pman1 = new ExplicitPairManager1(), pman2 = new ExplicitPairManager2();
CriticalSection.testApproaches(pman1, pman2);
}
}