OnJava8-Examples/lowlevel/EvenChecker.java

41 lines
1.2 KiB
Java
Raw Permalink Normal View History

2016-12-07 10:34:41 -08:00
// lowlevel/EvenChecker.java
// (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.
2017-01-12 16:49:36 -08:00
import java.util.*;
import java.util.stream.*;
2015-06-15 17:47:35 -07:00
import java.util.concurrent.*;
2017-01-11 16:18:57 -08:00
import onjava.TimedAbort;
2015-06-15 17:47:35 -07:00
public class EvenChecker implements Runnable {
2017-01-11 16:18:57 -08:00
private IntGenerator generator;
2015-06-15 17:47:35 -07:00
private final int id;
2017-01-11 16:18:57 -08:00
public EvenChecker(IntGenerator generator, int id) {
this.generator = generator;
this.id = id;
2015-06-15 17:47:35 -07:00
}
@Override public void run() {
2015-06-15 17:47:35 -07:00
while(!generator.isCanceled()) {
int val = generator.next();
if(val % 2 != 0) {
System.out.println(val + " not even!");
generator.cancel(); // Cancels all EvenCheckers
}
}
}
2017-01-11 16:18:57 -08:00
// Test any IntGenerator:
public static void test(IntGenerator gp, int count) {
2017-01-12 16:49:36 -08:00
List<CompletableFuture<Void>> checkers =
IntStream.range(0, count)
.mapToObj(i -> new EvenChecker(gp, i))
.map(CompletableFuture::runAsync)
.collect(Collectors.toList());
checkers.forEach(CompletableFuture::join);
2015-06-15 17:47:35 -07:00
}
// Default value for count:
2017-01-11 16:18:57 -08:00
public static void test(IntGenerator gp) {
2017-01-12 16:49:36 -08:00
new TimedAbort(4, "No odd numbers discovered");
2015-06-15 17:47:35 -07:00
test(gp, 10);
}
2015-09-07 11:44:36 -06:00
}