用java写一个时间片轮转算法
时间: 2024-01-04 13:04:49 浏览: 26
好的,以下是用 Java 实现时间片轮转算法的代码示例:
```java
import java.util.*;
public class RoundRobin {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// 输入进程数
System.out.println("请输入进程数:");
int n = sc.nextInt();
// 输入进程的到达时间和需要的运行时间
int[] arriveTime = new int[n];
int[] runTime = new int[n];
for (int i = 0; i < n; i++) {
System.out.println("请输入第" + (i + 1) + "个进程的到达时间和需要的运行时间:");
arriveTime[i] = sc.nextInt();
runTime[i] = sc.nextInt();
}
// 输入时间片大小
System.out.println("请输入时间片大小:");
int timeSlice = sc.nextInt();
// 初始化等待队列和完成队列
Queue<Integer> waitQueue = new LinkedList<>();
List<Integer> finishList = new ArrayList<>();
// 初始化当前时间和当前进程
int curTime = 0;
int curProcess = -1;
// 时间片轮转算法
while (!waitQueue.isEmpty() || curProcess != -1) {
// 将到达时间小于等于当前时间的进程加入等待队列
for (int i = 0; i < n; i++) {
if (arriveTime[i] <= curTime && !finishList.contains(i)) {
waitQueue.offer(i);
}
}
// 如果当前没有进程在运行,则取出等待队列中的第一个进程
if (curProcess == -1) {
curProcess = waitQueue.poll();
}
// 运行当前进程
runTime[curProcess] -= timeSlice;
curTime += timeSlice;
// 如果当前进程已经运行完毕,则加入完成队列
if (runTime[curProcess] <= 0) {
finishList.add(curProcess);
curProcess = -1;
}
// 如果当前进程还未运行完毕,则放回等待队列末尾
if (curProcess != -1) {
waitQueue.offer(curProcess);
curProcess = -1;
}
}
// 输出每个进程的完成时间
System.out.println("每个进程的完成时间分别为:");
for (int i = 0; i < n; i++) {
int finishTime = arriveTime[i];
for (int j = 0; j < finishList.size(); j++) {
if (finishList.get(j) == i) {
finishTime += (j + 1) * timeSlice;
break;
}
}
System.out.println("进程" + (i + 1) + ":" + finishTime);
}
}
}
```
注意:以上代码仅为示例,实际应用中可能需要进行更多的输入检查和错误处理。