OnJava8-Examples/concurrency/MutexEvenGenerator.java

25 lines
624 B
Java
Raw Normal View History

2015-04-20 15:36:01 -07:00
//: concurrency/MutexEvenGenerator.java
// Preventing thread collisions with mutexes.
2015-05-05 11:20:13 -07:00
// {TimeOutDuringTesting}
2015-04-20 15:36:01 -07:00
import java.util.concurrent.locks.*;
public class MutexEvenGenerator extends IntGenerator {
private int currentEvenValue = 0;
private Lock lock = new ReentrantLock();
2015-05-05 11:20:13 -07:00
@Override
2015-04-20 15:36:01 -07:00
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());
}
} ///:~