时间片轮转调度算法java
时间: 2023-11-21 14:56:05 浏览: 160
时间片轮转调度算法是一种常见的进程调度算法,它是一种基于时间片的调度算法,可以保证每个进程都能够公平地使用CPU。在Java中,可以通过以下方式实现时间片轮转调度算法:
```java
import java.util.LinkedList;
import java.util.Queue;
public class RoundRobin {
public static void main(String[] args) {
int[] process = {1, 2, 3, 4, 5};
int[] arrivalTime = {0, 1, 2, 3, 4};
int[] burstTime = {5, 3, 8, 6, 4};
int quantum = 3;
roundRobin(process, arrivalTime, burstTime, quantum);
}
public static void roundRobin(int[] process, int[] arrivalTime, int[] burstTime, int quantum) {
Queue<Integer> queue = new LinkedList<>();
int n = process.length;
int[] remainingTime = new int[n];
int[] waitingTime = new int[n];
int[] turnaroundTime = new int[n];
int totalWaitingTime = 0;
int totalTurnaroundTime = 0;
for (int i = 0; i < n; i++) {
remainingTime[i] = burstTime[i];
}
int time = 0;
queue.add(0);
while (!queue.isEmpty()) {
int processIndex = queue.poll();
if (remainingTime[processIndex] <= quantum) {
time += remainingTime[processIndex];
remainingTime[processIndex] = 0;
} else {
time += quantum;
remainingTime[processIndex] -= quantum;
}
while (processIndex < n && arrivalTime[processIndex] <= time) {
queue.add(processIndex++);
}
if (remainingTime[processIndex] > 0) {
queue.add(processIndex);
}
waitingTime[processIndex] = time - burstTime[processIndex] - arrivalTime[processIndex];
turnaroundTime[processIndex] = time - arrivalTime[processIndex];
}
for (int i = 0; i < n; i++) {
totalWaitingTime += waitingTime[i];
totalTurnaroundTime += turnaroundTime[i];
}
System.out.println("Process\tArrival Time\tBurst Time\tWaiting Time\tTurnaround Time");
for (int i = 0; i < n; i++) {
System.out.println(process[i] + "\t\t" + arrivalTime[i] + "\t\t" + burstTime[i] + "\t\t" + waitingTime[i] + "\t\t" + turnaroundTime[i]);
}
System.out.println("Average Waiting Time: " + (float) totalWaitingTime / n);
System.out.println("Average Turnaround Time: " + (float) totalTurnaroundTime / n);
}
}
```
上述代码中,我们使用了一个队列来存储进程,每次从队列中取出一个进程,并根据时间片的大小来执行进程。如果进程的剩余时间小于等于时间片,则执行完该进程;否则,将该进程重新加入队列中,等待下一次执行。同时,我们还计算了每个进程的等待时间和周转时间,并输出了平均等待时间和平均周转时间。
阅读全文