使用java代码写一个进程调度算法
时间: 2024-05-26 11:11:01 浏览: 69
java进程调度算法
4星 · 用户满意度95%
好的,我可以回答这个问题。进程调度算法是指操作系统如何为不同的进程分配 CPU 时间,以便最优化地利用 CPU 资源。以下是一个简单的Java代码示例,实现一个进程调度算法:
import java.util.*;
public class ProcessScheduler {
static Scanner scan = new Scanner(System.in);
static int n, quantum;
static String[] processName;
static int[] burstTime, waitingTime, turnaroundTime, remainingTime, arrivalTime;
static float avgWaitingTime, avgTurnaroundTime;
public static void main(String[] args) {
System.out.println("Enter the number of processes: ");
n = scan.nextInt();
processName = new String[n];
burstTime = new int[n];
waitingTime = new int[n];
turnaroundTime = new int[n];
remainingTime = new int[n];
arrivalTime = new int[n];
System.out.println("Enter the Process Name, Burst Time and Arrival Time for each process: ");
for (int i = 0; i < n; i++) {
System.out.println("\nProcess " + (i+1) + ": ");
System.out.println("Process Name: ");
processName[i] = scan.next();
System.out.println("Burst Time: ");
burstTime[i] = scan.nextInt();
System.out.println("Arrival Time: ");
arrivalTime[i] = scan.nextInt();
waitingTime[i] = 0;
turnaroundTime[i] = 0;
remainingTime[i] = burstTime[i];
}
System.out.println("\nEnter Time Quantum: ");
quantum = scan.nextInt();
// Applying Round Robin Algorithm
int t = 0, completed = 0;
boolean flag;
while (completed != n) {
flag = false;
for (int i = 0; i < n; i++) {
if (remainingTime[i] > 0) {
flag = true;
if (remainingTime[i] > quantum) {
t += quantum;
remainingTime[i] -= quantum;
} else {
t += remainingTime[i];
waitingTime[i] = t - burstTime[i] - arrivalTime[i];
remainingTime[i] = 0;
completed++;
}
}
}
if (!flag) {
break;
}
}
// Calculating Average Waiting Time and Turnaround Time
for (int i = 0; i < n; i++) {
turnaroundTime[i] = burstTime[i] + waitingTime[i];
avgWaitingTime += waitingTime[i];
avgTurnaroundTime += turnaroundTime[i];
}
avgWaitingTime /= n;
avgTurnaroundTime /= n;
System.out.println("\nProcess Scheduling Table:");
System.out.println("Process Name\tBurst Time\tArrival Time\tWaiting Time\tTurnaround Time");
for (int i = 0; i < n; i++) {
System.out.println(processName[i] + "\t\t" + burstTime[i] + "\t\t" + arrivalTime[i] + "\t\t" + waitingTime[i] + "\t\t" + turnaroundTime[i]);
}
System.out.println("\nAverage Waiting Time: " + avgWaitingTime);
System.out.println("Average Turnaround Time: " + avgTurnaroundTime);
}
}
阅读全文