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.

75 lines
1.7 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. System.out.println("Total Tasks: " + tasks.size());
  38. System.out.println("Threads Used:" + desiredThreads);
  39. for(int i = 0; i < desiredThreads; i++)
  40. {
  41. runners[i] = new Thread(()->
  42. {
  43. while(!tasks.isEmpty())
  44. {
  45. ReadTask t = tasks.remove(0);
  46. t.runTask();
  47. }
  48. });
  49. runners[i].start();
  50. }
  51. for(int i = 0; i < desiredThreads; i++)
  52. {
  53. try
  54. {
  55. runners[i].join();
  56. }
  57. catch (Exception e)
  58. {
  59. e.printStackTrace();
  60. }
  61. }
  62. }
  63. }