用java写时间片轮转调度算法
时间: 2024-03-09 10:21:30 浏览: 93
时间片轮转调度算法
4星 · 用户满意度95%
好的,时间片轮转调度算法(HRRN)的实现可以参考以下Java代码:
```
import java.util.*;
class Process {
String name;
int arrivalTime;
int burstTime;
int remainingTime;
int turnaroundTime;
int waitingTime;
int completionTime;
public Process(String name, int arrivalTime, int burstTime) {
this.name = name;
this.arrivalTime = arrivalTime;
this.burstTime = burstTime;
this.remainingTime = burstTime;
}
}
public class RoundRobinScheduler {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of processes: ");
int n = sc.nextInt();
Process[] processes = new Process[n];
for (int i = 0; i < n; i++) {
System.out.println("Enter the details of process " + (i + 1) + ":");
System.out.print("Name: ");
String name = sc.next();
System.out.print("Arrival time: ");
int arrivalTime = sc.nextInt();
System.out.print("Burst time: ");
int burstTime = sc.nextInt();
processes[i] = new Process(name, arrivalTime, burstTime);
}
System.out.print("Enter the time quantum: ");
int quantum = sc.nextInt();
roundRobin(processes, quantum);
sc.close();
}
public static void roundRobin(Process[] processes, int quantum) {
int time = 0;
int n = processes.length;
Queue<Process> readyQueue = new LinkedList<Process>();
for (int i = 0; i < n; i++) {
readyQueue.add(processes[i]);
}
System.out.println("\nGantt chart:");
System.out.print(0);
while (!readyQueue.isEmpty()) {
Process p = readyQueue.poll();
if (p.remainingTime > quantum) {
time += quantum;
p.remainingTime -= quantum;
System.out.print(" -- " + p.name + " -- " + time);
readyQueue.add(p);
} else {
time += p.remainingTime;
p.completionTime = time;
p.turnaroundTime = p.completionTime - p.arrivalTime;
p.waitingTime = p.turnaroundTime - p.burstTime;
System.out.print(" -- " + p.name + " -- " + time);
}
}
System.out.println();
printTable(processes);
}
public static void printTable(Process[] processes) {
double avgTurnaroundTime = 0;
double avgWaitingTime = 0;
System.out.println("\nProcess\tAT\tBT\tCT\tTAT\tWT");
for (Process p : processes) {
System.out.println(p.name + "\t" + p.arrivalTime + "\t" + p.burstTime + "\t" + p.completionTime + "\t" + p.turnaroundTime + "\t" + p.waitingTime);
avgTurnaroundTime += p.turnaroundTime;
avgWaitingTime += p.waitingTime;
}
System.out.println("\nAverage turnaround time: " + (avgTurnaroundTime / processes.length));
System.out.println("Average waiting time: " + (avgWaitingTime / processes.length));
}
}
```
这段代码中,我们首先定义了一个 Process 类,表示待调度的进程;然后实现了一个 roundRobin() 函数,其中用到了队列(LinkedList 类)作为 ready queue,并按照时间片轮转的策略进行调度;最后我们实现了一个 printTable() 函数,输出每个进程的相关信息,并计算平均周转时间和平均等待时间。
阅读全文