OnJava8-Examples/lowlevel/EvenChecker.java

37 lines
1.0 KiB
Java
Raw Normal View History

2016-12-07 10:34:41 -08:00
// lowlevel/EvenChecker.java
2015-12-15 11:47:04 -08:00
// (c)2016 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.
2015-06-15 17:47:35 -07:00
import java.util.concurrent.*;
public class EvenChecker implements Runnable {
2015-11-03 12:00:44 -08:00
private IntSupplier generator;
2015-06-15 17:47:35 -07:00
private final int id;
2015-11-03 12:00:44 -08:00
public EvenChecker(IntSupplier g, int ident) {
2015-06-15 17:47:35 -07:00
generator = g;
id = ident;
}
@Override
public void run() {
while(!generator.isCanceled()) {
int val = generator.next();
if(val % 2 != 0) {
System.out.println(val + " not even!");
generator.cancel(); // Cancels all EvenCheckers
}
}
}
2015-11-03 12:00:44 -08:00
// Test any type of IntSupplier:
public static void test(IntSupplier gp, int count) {
2015-06-15 17:47:35 -07:00
System.out.println("Press Control-C to exit");
2016-01-25 18:05:55 -08:00
ExecutorService es = Executors.newCachedThreadPool();
2015-06-15 17:47:35 -07:00
for(int i = 0; i < count; i++)
2016-01-25 18:05:55 -08:00
es.execute(new EvenChecker(gp, i));
es.shutdown();
2015-06-15 17:47:35 -07:00
}
// Default value for count:
2015-11-03 12:00:44 -08:00
public static void test(IntSupplier gp) {
2015-06-15 17:47:35 -07:00
test(gp, 10);
}
2015-09-07 11:44:36 -06:00
}