Advertisement
Guest User

Untitled

a guest
Feb 10th, 2016
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.78 KB | None | 0 0
  1. import java.util.ArrayList;
  2. import java.util.List;
  3. import java.util.Random;
  4. import java.util.concurrent.ExecutionException;
  5. import java.util.concurrent.Executors;
  6. import java.util.concurrent.Future;
  7. import java.util.concurrent.ThreadPoolExecutor;
  8.  
  9. public class CallableExample
  10. {
  11. public static void main(String[] args)
  12. {
  13. ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(4);
  14.  
  15. List<Future<Integer>> resultList = new ArrayList<>();
  16.  
  17. Random random = new Random();
  18.  
  19. for (int i=0; i<10; i++)
  20. {
  21. Integer number = random.nextInt(100);
  22. FactorialCalculator calculator = new FactorialCalculator(number);
  23. Future<Integer> result = executor.submit(calculator);
  24. resultList.add(result);
  25. }
  26.  
  27. for(Future<Integer> future : resultList)
  28. {
  29. try
  30. {
  31. System.out.println("Future result is - " + " - " + future.get() + "; And Task done is " + future.isDone());
  32. }
  33. catch (InterruptedException | ExecutionException e)
  34. {
  35. e.printStackTrace();
  36. }
  37. }
  38. //shut down the executor service now
  39. executor.shutdown();
  40. }
  41. }
  42.  
  43.  
  44.  
  45.  
  46.  
  47.  
  48.  
  49.  
  50. import java.util.concurrent.Callable;
  51. import java.util.concurrent.TimeUnit;
  52.  
  53. class FactorialCalculator implements Callable<Integer>
  54. {
  55.  
  56. private Integer number;
  57.  
  58. public FactorialCalculator(Integer number) {
  59. this.number = number;
  60. }
  61.  
  62. @Override
  63. public Integer call() throws Exception {
  64. int i = 0;
  65. while(!Thread.terminated()) {
  66. i++;
  67. }
  68. return i;
  69. }
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement