mirror of
https://github.com/TheAlgorithms/Java.git
synced 2025-07-08 02:04:31 +08:00
Add Preemptive Priority Scheduling Algorithm (#4323)
This commit is contained in:

committed by
GitHub

parent
af80c8005d
commit
4bcddd323c
@ -0,0 +1,54 @@
|
||||
package com.thealgorithms.scheduling;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* Preemptive Priority Scheduling Algorithm
|
||||
* @author [Bama Charan Chhandogi](https://www.github.com/BamaCharanChhandogi)
|
||||
*/
|
||||
|
||||
class Process {
|
||||
String name;
|
||||
int arrivalTime;
|
||||
int burstTime;
|
||||
int priority;
|
||||
|
||||
public Process(String name, int arrivalTime, int burstTime, int priority) {
|
||||
this.name = name;
|
||||
this.arrivalTime = arrivalTime;
|
||||
this.burstTime = burstTime;
|
||||
this.priority = priority;
|
||||
}
|
||||
}
|
||||
|
||||
public class PreemptivePriorityScheduling {
|
||||
public static List<String> preemptivePriorityScheduling(List<Process> processes) {
|
||||
List<String> ganttChart = new ArrayList<>();
|
||||
PriorityQueue<Process> readyQueue = new PriorityQueue<>(Comparator.comparingInt(p -> - p.priority));
|
||||
|
||||
int currentTime = 0;
|
||||
|
||||
while (!processes.isEmpty() || !readyQueue.isEmpty()) {
|
||||
while (!processes.isEmpty() && processes.get(0).arrivalTime <= currentTime) {
|
||||
readyQueue.add(processes.remove(0));
|
||||
}
|
||||
|
||||
if (!readyQueue.isEmpty()) {
|
||||
Process currentProcess = readyQueue.poll();
|
||||
|
||||
ganttChart.add(currentProcess.name);
|
||||
currentProcess.burstTime--;
|
||||
|
||||
if (currentProcess.burstTime > 0) {
|
||||
readyQueue.add(currentProcess);
|
||||
}
|
||||
} else {
|
||||
ganttChart.add("Idle");
|
||||
}
|
||||
|
||||
currentTime++;
|
||||
}
|
||||
|
||||
return ganttChart;
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user