-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathTaskManager.java
More file actions
87 lines (76 loc) · 2 KB
/
Copy pathTaskManager.java
File metadata and controls
87 lines (76 loc) · 2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
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];
for(int i = 0; i < desiredThreads; i++)
{
runners[i] = new Thread(()->
{
ReadTask t = null;
while(true)
{
//need synchronized block to prevent
//race condition
synchronized (tasks)
{
if(!tasks.isEmpty())
t = tasks.remove(0);
}
if(t == null)
{
break;
}
else
{
t.runTask();
t = null;
}
}
});
runners[i].start();
}
for(int i = 0; i < desiredThreads; i++)
{
try
{
runners[i].join();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
}