-
Notifications
You must be signed in to change notification settings - Fork 19.9k
/
Copy pathPreemptivePriorityScheduling.java
60 lines (50 loc) · 2.03 KB
/
PreemptivePriorityScheduling.java
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
package com.thealgorithms.scheduling;
import com.thealgorithms.devutils.entities.ProcessDetails;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.PriorityQueue;
/**
* Preemptive Priority Scheduling Algorithm
*
* @author [Bama Charan Chhandogi](https://www.github.com/BamaCharanChhandogi)
*/
public class PreemptivePriorityScheduling {
protected final List<ProcessDetails> processes;
protected final List<String> ganttChart;
public PreemptivePriorityScheduling(Collection<ProcessDetails> processes) {
this.processes = new ArrayList<>(processes);
this.ganttChart = new ArrayList<>();
}
public void scheduleProcesses() {
PriorityQueue<ProcessDetails> readyQueue = new PriorityQueue<>(Comparator.comparingInt(ProcessDetails::getPriority).reversed().thenComparingInt(ProcessDetails::getArrivalTime));
int currentTime = 0;
List<ProcessDetails> arrivedProcesses = new ArrayList<>();
while (!processes.isEmpty() || !readyQueue.isEmpty()) {
updateArrivedProcesses(currentTime, arrivedProcesses);
readyQueue.addAll(arrivedProcesses);
arrivedProcesses.clear();
if (!readyQueue.isEmpty()) {
ProcessDetails currentProcess = readyQueue.poll();
ganttChart.add(currentProcess.getProcessId());
currentProcess.setBurstTime(currentProcess.getBurstTime() - 1);
if (currentProcess.getBurstTime() > 0) {
readyQueue.add(currentProcess);
}
} else {
ganttChart.add("Idle");
}
currentTime++;
}
}
private void updateArrivedProcesses(int currentTime, List<ProcessDetails> arrivedProcesses) {
processes.removeIf(process -> {
if (process.getArrivalTime() <= currentTime) {
arrivedProcesses.add(process);
return true;
}
return false;
});
}
}