我面临的问题是我找不到计算开始时间的方法(在代码中称为startedAt),所以我能够计算周转时间和等待时间。我使用的逻辑如下:
- 我们首先复制突发时间“BurstTime”来存储剩余的突发时间remBurstTime。
- 根据优先级对进程进行排序(优先级越低表示优先级越高)
- 先到达的元素会一直运行,直到到达优先级较高的进程的到达时间,即我们从前一个进程的突发时间中减去后一个进程的到达时间。
- 运行 FCFS。
进程类
class ProcessInfo{
public int ArrivalTime;
public int BurstTime ;
public int remBurstTime ;
public int Priority ;
public int TurnAroundTime;
public int CompletionTime;
public double WaitTime;
public ProcessInfo(int ArrivalTime , int BurstTime , int priority){
this.ArrivalTime = ArrivalTime ;
this.BurstTime = BurstTime ;
this.Priority = priority ;
}
}
抢占式优先方法
public static void PriorityPreemptive(ProcessInfo[] process) {
for (ProcessInfo processInfo : process) processInfo.remBurstTime = processInfo.BurstTime;
for (int i = 0; i < process.length; i++) {
for (int j = i + 1; j < process.length; ++j) {
if (process[i].Priority > process[j].Priority) {
ProcessInfo temp = process[j];
process[j] = process[i];
process[i] = temp;
if (process[i].ArrivalTime < process[j].ArrivalTime) {
process[i].remBurstTime = process[i].BurstTime - process[j].ArrivalTime ;
}
}
}
}
FCFS 类。
public static void FCFS(ProcessInfo[] process) {
double TurnAroundTime = 0;
double TotalTime = 0;
int StartedAt = 0;
if (process[0].ArrivalTime != StartedAt) {
StartedAt = process[0].ArrivalTime;//initialize the startedAt time
}
//Now let's compute the avgTime and turnAroundTime of each process
for (ProcessInfo processInfo : process) {
processInfo.CompletionTime = StartedAt + processInfo.remBurstTime;//completion time (remBurst is the remaining burst time)
StartedAt = processInfo.CompletionTime; // here is the issue
processInfo.TurnAroundTime = processInfo.CompletionTime - processInfo.ArrivalTime;
processInfo.WaitTime = processInfo.TurnAroundTime - processInfo.BurstTime;
TotalTime += processInfo.WaitTime; // Calculate the total turnover time, and the value stored in avgTotalTime is the total turnover time
TurnAroundTime += processInfo.TurnAroundTime; // Calculate the total weighted turnover time, and the value stored in avgPowerTime is the total weighted turnover time
System.out.println("Started :\t " + StartedAt + " Completion :\t " + processInfo.CompletionTime + " TurnAround :\t "+ processInfo.TurnAroundTime + " WaitTime :\t"+ processInfo.WaitTime);
}
double avgWaitingTime = TotalTime / process.length;
double avgTurnAroundTime = TurnAroundTime / process.length;
System.out.println("The Average Waiting Time is :\t" + avgWaitingTime + "\nThe Average TurnAroundTime is :\t " + avgTurnAroundTime);
}
我用这个算法得到的结果非常接近,我只需要找到正确的方法来计算StartedAt以便其他时间(等待时间、周转时间)变得正确。
我希望你能帮我解决这个问题,在此先感谢。