Repository where I mostly put random python scripts.
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.

86 lines
2.0 KiB

  1. import java.util.List;
  2. import java.util.Vector;
  3. /**
  4. * A class which enables user to run a large chunk of
  5. * tasks in parallel efficiently.
  6. *
  7. * @author Jeffery 1-29-19
  8. */
  9. public class TaskManager
  10. {
  11. /** Number of threads to use at once */
  12. private int threadCount;
  13. /** Meaningless tasks to run in parallel */
  14. private List<ReadTask> tasks;
  15. public TaskManager(int threadCount)
  16. {
  17. this.threadCount = threadCount;
  18. //using vectors because they are thread safe
  19. this.tasks = new Vector<>();
  20. }
  21. public void addTask(ReadTask t)
  22. {
  23. tasks.add(t);
  24. }
  25. /**
  26. * This is the fun method.
  27. *
  28. * This will run all of the tasks in parallel using the
  29. * desired amount of threads untill all of the jobs are
  30. * complete.
  31. */
  32. public void runTasks()
  33. {
  34. int desiredThreads = threadCount > tasks.size() ?
  35. tasks.size() : threadCount;
  36. Thread[] runners = new Thread[desiredThreads];
  37. for(int i = 0; i < desiredThreads; i++)
  38. {
  39. runners[i] = new Thread(()->
  40. {
  41. ReadTask t = null;
  42. while(true)
  43. {
  44. //need synchronized block to prevent
  45. //race condition
  46. synchronized (tasks)
  47. {
  48. if(!tasks.isEmpty())
  49. t = tasks.remove(0);
  50. }
  51. if(t == null)
  52. {
  53. break;
  54. }
  55. else
  56. {
  57. t.runTask();
  58. t = null;
  59. }
  60. }
  61. });
  62. runners[i].start();
  63. }
  64. for(int i = 0; i < desiredThreads; i++)
  65. {
  66. try
  67. {
  68. runners[i].join();
  69. }
  70. catch (Exception e)
  71. {
  72. e.printStackTrace();
  73. }
  74. }
  75. }
  76. }