|
| 1 | +package sporadic.java_async_method_example.future; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.Date; |
| 5 | +import java.util.List; |
| 6 | +import java.util.concurrent.Callable; |
| 7 | +import java.util.concurrent.ExecutionException; |
| 8 | +import java.util.concurrent.ExecutorService; |
| 9 | +import java.util.concurrent.Executors; |
| 10 | +import java.util.concurrent.Future; |
| 11 | + |
| 12 | +public class MainApp { |
| 13 | + |
| 14 | + public static void main(String... args) { |
| 15 | + //Played around with different Executors, have different effects, pretty cool! |
| 16 | + ExecutorService executor = //Executors.newFixedThreadPool(5) |
| 17 | +// Executors.newSingleThreadExecutor() |
| 18 | +// Executors.newCachedThreadPool() |
| 19 | + Executors.newScheduledThreadPool(15); |
| 20 | + /**thread pool account could be a bottleneck when it's smaller than 10 which is the max in the below for loop. |
| 21 | + * so when I changed the ThreadPool size to 15, then ALL Future objects got returned at the same time! Cool!*/ |
| 22 | + |
| 23 | + List<Future<String>> list = new ArrayList<Future<String>>(); |
| 24 | + |
| 25 | + Callable<String> callable = new MyCallable(); |
| 26 | + |
| 27 | + for (int i = 0; i < 10; i++) { |
| 28 | + Future<String> future = executor.submit(callable); |
| 29 | + while (!future.isDone()) { |
| 30 | + try { |
| 31 | + Thread.sleep(500); |
| 32 | + } catch (InterruptedException e) { |
| 33 | + e.printStackTrace(); |
| 34 | + } |
| 35 | + System.out.println("callable: " + callable + " is not done yet, please wait..."); |
| 36 | + } |
| 37 | + System.out.println("callable: " + callable + " is already done and is being added into the list.\n"); |
| 38 | + list.add(future); |
| 39 | + } |
| 40 | + |
| 41 | + for(Future<String> future : list){ |
| 42 | + try { |
| 43 | + System.out.println(new Date() + " " + future.get()); |
| 44 | + } catch (InterruptedException | ExecutionException e) { |
| 45 | + e.printStackTrace(); |
| 46 | + } |
| 47 | + } |
| 48 | + executor.shutdown(); |
| 49 | + System.out.println("That's the end of the program!"); |
| 50 | + } |
| 51 | + |
| 52 | +} |
0 commit comments