1 package com.freemindcafe.concurrency.sample2;
3 import java.util.Arrays;
5 import java.util.concurrent.Callable;
6 import java.util.concurrent.ExecutionException;
7 import java.util.concurrent.ExecutorService;
8 import java.util.concurrent.Future;
9 import java.util.concurrent.LinkedBlockingQueue;
10 import java.util.concurrent.ThreadPoolExecutor;
11 import java.util.concurrent.TimeUnit;
13 import junit.framework.Assert;
18 public void simple_pool_with_callable()
throws InterruptedException, ExecutionException{
19 Callable<Integer> c1 = ()->1;
20 Callable<Integer> c2 = ()->1;
22 ExecutorService executor =
new ThreadPoolExecutor(1, 1, 0, TimeUnit.HOURS,
new LinkedBlockingQueue<Runnable>());
23 Future<Integer> f1 = executor.submit(c1);
24 Future<Integer> f2 = executor.submit(c2);
26 System.out.println(executor.awaitTermination(1, TimeUnit.MINUTES));
28 Assert.assertEquals(2, f1.get()+f2.get());
33 public void invoke_all()
throws InterruptedException, ExecutionException{
34 Callable<Integer> c1 = ()->1;
35 Callable<Integer> c2 = ()->1;
37 ExecutorService executor =
new ThreadPoolExecutor(1, 1, 0, TimeUnit.HOURS,
new LinkedBlockingQueue<Runnable>());
38 List<Future<Integer>> results = executor.invokeAll(Arrays.asList(c1,c2));
40 System.out.println(executor.awaitTermination(1, TimeUnit.MINUTES));
42 Assert.assertEquals(2, results.stream().mapToInt(f->{
try{return f.get();}
catch(Exception ex){return -1;}}).sum());
49 public void test3() throws InterruptedException, ExecutionException{
50 Callable<Integer> c1 = () -> {Thread.sleep(10000);
return 1;};
51 Callable<Integer> c2 = ()->1;
53 ExecutorService executor =
new ThreadPoolExecutor(1, 1, 0, TimeUnit.HOURS,
new LinkedBlockingQueue<Runnable>());
54 List<Future<Integer>> results = executor.invokeAll(Arrays.asList(c1,c2));
56 System.out.println(executor.awaitTermination(1, TimeUnit.SECONDS));
57 System.out.println(
"hi");
59 Assert.assertEquals(2, results.stream().mapToInt(f->{
try{return f.get();}
catch(Exception ex){return -1;}}).sum());