java实现短作业优先调度算法(附完整源码)
时间: 2023-10-15 21:02:12 浏览: 117
短作业优先调度算法.docx
以下是Java实现短作业优先调度算法的完整源代码:
```
import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;
public class SJF {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("请输入进程数:");
int n = sc.nextInt();
int[][] processes = new int[n][3];
for (int i = 0; i < n; i++) {
System.out.println("请输入第" + (i + 1) + "个进程的信息(到达时间,服务时间):");
processes[i][0] = sc.nextInt();
processes[i][1] = sc.nextInt();
processes[i][2] = i + 1;
}
Arrays.sort(processes, Comparator.comparingInt(p -> p[0]));
int[] finishTime = new int[n];
int[] waitingTime = new int[n];
int[] turnaroundTime = new int[n];
int totalWaitingTime = 0;
int totalTurnaroundTime = 0;
for (int i = 0, currentTime = 0; i < n; i++) {
int[] process = processes[i];
currentTime = Math.max(currentTime, process[0]);
finishTime[i] = currentTime + process[1];
turnaroundTime[i] = finishTime[i] - process[0];
waitingTime[i] = turnaroundTime[i] - process[1];
totalWaitingTime += waitingTime[i];
totalTurnaroundTime += turnaroundTime[i];
currentTime = finishTime[i];
}
System.out.println("进程\t到达时间\t服务时间\t完成时间\t等待时间\t周转时间");
for (int i = 0; i < n; i++) {
System.out.printf("%d\t%d\t\t%d\t\t%d\t\t%d\t\t%d\n", processes[i][2], processes[i][0], processes[i][1], finishTime[i], waitingTime[i], turnaroundTime[i]);
}
System.out.printf("平均等待时间:%.2f\n", (double) totalWaitingTime / n);
System.out.printf("平均周转时间:%.2f\n", (double) totalTurnaroundTime / n);
}
}
```
运行程序后,根据提示输入进程数和每个进程的到达时间、服务时间即可得到每个进程的完成时间、等待时间、周转时间以及平均等待时间和平均周转时间。
阅读全文