时间片轮转调度算法题java
时间: 2023-12-03 18:40:08 浏览: 100
以下是Java实现基于优先数的时间片轮转调度算法的代码示例:
```java
import java.util.*;
public class TimeSliceScheduler {
public static void main(String[] args) {
// 进程控制块列表
List<PCB> pcbList = new ArrayList<>();
// 添加5个进程
pcbList.add(new PCB("A", 0, 3, 1));
pcbList.add(new PCB("B", 2, 6, 2));
pcbList.add(new PCB("C", 4, 4, 3)); pcbList.add(new PCB("D", 6, 5, 4));
pcbList.add(new PCB("E", 8, 2, 5));
// 时间片长度
int timeSlice = 2; // 当前时间
int currentTime = 0;
// 运行队列
Queue<PCB> runQueue = new LinkedList<>();
// 结果列表
List<String> resultList = new ArrayList<>();
// 按照到达时间排序
Collections.sort(pcbList, new Comparator<PCB>() {
@Override
public int compare(PCB o1, PCB o2) {
return o1.arriveTime - o2.arriveTime;
}
});
// 调度
while (!pcbList.isEmpty() || !runQueue.isEmpty()) {
// 将到达时间小于等于当前时间的进程加入运行队列
while (!pcbList.isEmpty() && pcbList.get(0).arriveTime <= currentTime) {
runQueue.offer(pcbList.remove(0));
}
// 如果运行队列为空,则时间跳转到下一个进程到达时间
if (runQueue.isEmpty()) {
currentTime = pcbList.get(0).arriveTime;
continue;
}
// 取出队首进程
PCB currentPCB = runQueue.poll();
// 执行时间片
int executeTime = Math.min(timeSlice, currentPCB.remainTime); // 更新进程信息
currentPCB.remainTime -= executeTime;
currentPCB.priority -= 1;
// 如果进程还未执行完,则重新加入运行队列
if (currentPCB.remainTime > 0) {
runQueue.offer(currentPCB);
}
// 记录结果
resultList.add(currentPCB.name + " " + currentTime + " " + executeTime);
// 更新当前时间
currentTime += executeTime;
}
// 输出结果
for (String result : resultList) {
System.out.println(result);
}
}
}
// 进程控制块类
class PCB {
String name; // 进程名
int arriveTime; // 到达时间
int remainTime; // 剩余执行时间
int priority; // 优先数
public PCB(String name, int arriveTime, int remainTime, int priority) {
this.name = name;
this.arriveTime = arriveTime;
this.remainTime = remainTime;
this.priority = priority;
}
}
```
阅读全文