OnJava8-Examples/lowlevel/MutexEvenProducer.java
2017-01-12 11:15:03 -08:00

29 lines
804 B
Java

// lowlevel/MutexEvenProducer.java
// (c)2017 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.
// Preventing thread collisions with mutexes
// {IgnoreOutput} // No output validation
import java.util.concurrent.locks.*;
import onjava.Nap;
public class MutexEvenProducer extends IntGenerator {
private int currentEvenValue = 0;
private Lock lock = new ReentrantLock();
@Override
public int next() {
lock.lock();
try {
++currentEvenValue;
new Nap(10); // Cause failure faster
++currentEvenValue;
return currentEvenValue;
} finally {
lock.unlock();
}
}
public static void main(String[] args) {
EvenChecker.test(new MutexEvenProducer());
}
}