forked from teddyzhang1976/ThinkInJava4thSampleCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMutexEvenGenerator.java
More file actions
24 lines (23 loc) · 648 Bytes
/
MutexEvenGenerator.java
File metadata and controls
24 lines (23 loc) · 648 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
//: concurrency/MutexEvenGenerator.java
package concurrency; /* Added by Eclipse.py */
// Preventing thread collisions with mutexes.
// {RunByHand}
import java.util.concurrent.locks.*;
public class MutexEvenGenerator extends IntGenerator {
private int currentEvenValue = 0;
private Lock lock = new ReentrantLock();
public int next() {
lock.lock();
try {
++currentEvenValue;
Thread.yield(); // Cause failure faster
++currentEvenValue;
return currentEvenValue;
} finally {
lock.unlock();
}
}
public static void main(String[] args) {
EvenChecker.test(new MutexEvenGenerator());
}
} ///:~