2017-01-11 16:18:57 -08:00
|
|
|
// lowlevel/SynchronizedEvenProducer.java
|
2021-01-31 15:42:31 -07:00
|
|
|
// (c)2021 MindView LLC: see Copyright.txt
|
2016-07-05 14:46:09 -06: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-07-05 14:46:09 -06:00
|
|
|
// Simplifying mutexes with the synchronized keyword
|
2017-01-11 16:18:57 -08:00
|
|
|
import onjava.Nap;
|
2016-07-05 14:46:09 -06:00
|
|
|
|
|
|
|
public class
|
2017-01-11 16:18:57 -08:00
|
|
|
SynchronizedEvenProducer extends IntGenerator {
|
2016-07-05 14:46:09 -06:00
|
|
|
private int currentEvenValue = 0;
|
2021-01-31 15:42:31 -07:00
|
|
|
@Override public synchronized int next() {
|
2016-07-05 14:46:09 -06:00
|
|
|
++currentEvenValue;
|
2017-01-22 16:48:11 -08:00
|
|
|
new Nap(0.01); // Cause failure faster
|
2016-07-05 14:46:09 -06:00
|
|
|
++currentEvenValue;
|
|
|
|
return currentEvenValue;
|
|
|
|
}
|
|
|
|
public static void main(String[] args) {
|
2017-01-11 16:18:57 -08:00
|
|
|
EvenChecker.test(new SynchronizedEvenProducer());
|
2016-07-05 14:46:09 -06:00
|
|
|
}
|
|
|
|
}
|
2017-01-12 16:49:36 -08:00
|
|
|
/* Output:
|
|
|
|
No odd numbers discovered
|
|
|
|
*/
|