Repository where I mostly put random python scripts.
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
 
 
 
 

76 lignes
1.7 KiB

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<ReadTask> 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();
}
}
}
}