import java.util.List; import java.util.Vector; /** * A class which enables user to run a large chunk of * tasks in parallel efficiently. * * @author Jeffery 1-29-19 */ public class TaskManager { /** Number of threads to use at once */ private int threadCount; /** Meaningless tasks to run in parallel */ private List tasks; public TaskManager(int threadCount) { this.threadCount = threadCount; //using vectors because they are thread safe this.tasks = new Vector<>(); } public void addTask(ReadTask t) { tasks.add(t); } /** * This is the fun method. * * This will run all of the tasks in parallel using the * desired amount of threads untill all of the jobs are * complete. */ public void runTasks() { int desiredThreads = threadCount > tasks.size() ? tasks.size() : threadCount; Thread[] runners = new Thread[desiredThreads]; System.out.println("Total Tasks: " + tasks.size()); System.out.println("Threads Used:" + desiredThreads); for(int i = 0; i < desiredThreads; i++) { runners[i] = new Thread(()-> { while(!tasks.isEmpty()) { ReadTask t = tasks.remove(0); t.runTask(); } }); runners[i].start(); } for(int i = 0; i < desiredThreads; i++) { try { runners[i].join(); } catch (Exception e) { e.printStackTrace(); } } } }