Code for a blogpost
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

66 lines
1.8 KiB

  1. package net.jrtechs;
  2. import java.util.*;
  3. import java.util.concurrent.ConcurrentSkipListSet;
  4. import java.util.stream.Collectors;
  5. import java.util.stream.IntStream;
  6. public class Manager<E> extends ParallelExecutor<E>
  7. {
  8. /** Number of threads to use at once */
  9. private final int threadCount;
  10. public Manager(int threadCount)
  11. {
  12. this.threadCount = threadCount;
  13. }
  14. /**
  15. * This is the fun method.
  16. *
  17. * This will run all of the tasks in parallel using the
  18. * desired amount of threads until all of the jobs are
  19. * complete.
  20. * @return
  21. * @param tasks
  22. */
  23. public List<E> runTasks(Vector<Work<E>> tasks)
  24. {
  25. List<E> results = new Vector<>();
  26. Queue<Integer> taskQueue = new LinkedList<>();
  27. taskQueue.addAll(IntStream.range(0, tasks.size())
  28. .boxed().collect(Collectors.toList()));
  29. int desiredThreads = Math.min(threadCount, tasks.size());
  30. Thread[] runners = new Thread[desiredThreads];
  31. for(int i = 0; i < desiredThreads; i++)
  32. {
  33. runners[i] = new Thread(()->
  34. {
  35. Work<E> t;
  36. while(true)
  37. {
  38. Integer nextTask;
  39. synchronized (taskQueue)
  40. {
  41. nextTask = taskQueue.poll();
  42. }
  43. if(nextTask == null)
  44. return;
  45. results.add(tasks.get(nextTask).runTask());
  46. }
  47. });
  48. runners[i].start();
  49. }
  50. for(Thread t: runners)
  51. {
  52. try
  53. {
  54. t.join();
  55. } catch (InterruptedException e) {
  56. e.printStackTrace();
  57. }
  58. }
  59. return results;
  60. }
  61. }