57 lines
1.9 KiB
Java
57 lines
1.9 KiB
Java
import java.util.List;
|
|
import java.util.concurrent.ExecutionException;
|
|
import java.util.concurrent.ExecutorService;
|
|
import java.util.concurrent.Executors;
|
|
import java.util.concurrent.Future;
|
|
import java.util.concurrent.TimeUnit;
|
|
|
|
public class SimpleExecutorCompletionServiceTester_with_take extends Concurrent<Integer> {
|
|
|
|
private static final int N_TASKS_PER_TESTER = 3;
|
|
private static final ExecutorService ecs = Executors.newCachedThreadPool();
|
|
private static final SimpleExecutorCompletionService_with_take<Integer> secs =
|
|
new SimpleExecutorCompletionService_with_take<>(ecs);
|
|
|
|
public SimpleExecutorCompletionServiceTester_with_take(Integer[] args) {
|
|
super(args);
|
|
}
|
|
|
|
private static int sleepAndReturnTime(int sleepTimeMs) throws InterruptedException {
|
|
Thread.sleep(sleepTimeMs);
|
|
return sleepTimeMs;
|
|
}
|
|
|
|
public static void main(String[] args) {
|
|
new SimpleExecutorCompletionServiceTester_with_take(new Integer[]{1, 2, 3, 4, 5}).run();
|
|
List<Runnable> unstartedTasks = ecs.shutdownNow();
|
|
if (!unstartedTasks.isEmpty())
|
|
System.out.println("Still some unstarted tasks left after end of all tester threads!?");
|
|
try {
|
|
ecs.awaitTermination(1, TimeUnit.SECONDS);
|
|
} catch (InterruptedException e) {
|
|
e.printStackTrace();
|
|
}
|
|
}
|
|
|
|
@Override
|
|
protected void perform(Integer testerNr) {
|
|
|
|
for (int i = 0; i < N_TASKS_PER_TESTER; ++i) {
|
|
secs.submit(() -> sleepAndReturnTime(10+10*(int)(Math.random()*10)));
|
|
// Note that submit's result is ignored here
|
|
}
|
|
|
|
for (int i = 0; i < N_TASKS_PER_TESTER; ++i) {
|
|
try {
|
|
Future<Integer> fut = secs.take();
|
|
System.out.println("Tester " + testerNr + " received result " + fut.get());
|
|
} catch (InterruptedException | ExecutionException e) {
|
|
e.printStackTrace();
|
|
return;
|
|
}
|
|
}
|
|
System.out.println("Tester " + testerNr + " ends.");
|
|
}
|
|
|
|
}
|