2017-01-11 16:18:57 -08:00
|
|
|
// lowlevel/MutexEvenProducer.java
|
2021-01-31 15:42:31 -07:00
|
|
|
// (c)2021 MindView LLC: see Copyright.txt
|
2015-11-15 15:51:35 -08:00
|
|
|
// We make no guarantees that this code is fit for any purpose.
|
2016-09-23 13:23:35 -06:00
|
|
|
// Visit http://OnJava8.com for more book information.
|
2016-01-25 18:05:55 -08:00
|
|
|
// Preventing thread collisions with mutexes
|
2015-06-15 17:47:35 -07:00
|
|
|
import java.util.concurrent.locks.*;
|
2017-01-12 11:15:03 -08:00
|
|
|
import onjava.Nap;
|
2015-06-15 17:47:35 -07:00
|
|
|
|
2017-01-11 16:18:57 -08:00
|
|
|
public class MutexEvenProducer extends IntGenerator {
|
2015-06-15 17:47:35 -07:00
|
|
|
private int currentEvenValue = 0;
|
|
|
|
private Lock lock = new ReentrantLock();
|
2021-01-31 15:42:31 -07:00
|
|
|
@Override public int next() {
|
2015-06-15 17:47:35 -07:00
|
|
|
lock.lock();
|
|
|
|
try {
|
|
|
|
++currentEvenValue;
|
2017-01-22 16:48:11 -08:00
|
|
|
new Nap(0.01); // Cause failure faster
|
2015-06-15 17:47:35 -07:00
|
|
|
++currentEvenValue;
|
|
|
|
return currentEvenValue;
|
|
|
|
} finally {
|
|
|
|
lock.unlock();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
public static void main(String[] args) {
|
2017-01-11 16:18:57 -08:00
|
|
|
EvenChecker.test(new MutexEvenProducer());
|
2015-06-15 17:47:35 -07:00
|
|
|
}
|
2015-09-07 11:44:36 -06:00
|
|
|
}
|
2017-01-12 16:49:36 -08:00
|
|
|
/*
|
|
|
|
No odd numbers discovered
|
|
|
|
*/
|