OnJava8-Examples/concurrency/EvenChecker.java

37 lines
1.1 KiB
Java
Raw Normal View History

2015-09-07 11:44:36 -06:00
// concurrency/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.
// Visit http://mindviewinc.com/Books/OnJava/ 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");
ExecutorService exec = Executors.newCachedThreadPool();
for(int i = 0; i < count; i++)
exec.execute(new EvenChecker(gp, i));
exec.shutdown();
}
// 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
}