进程调度-时间片轮转法(Java简单实现)

时间:2021-10-21 21:16:09

分时系统中,最简单也较常用的调度方法即基于时间片(round robin)的轮转调度算法。

该算法采取非常公平的处理机分配方式,让就绪队列上的每个进程每次仅运行一个时间片。

如果就绪队列上有n个进程,则每个进程每次大约都可获得1/n的处理机时间。


实现效果:(只列出输入和最终输出,省略中间过程)

进程调度-时间片轮转法(Java简单实现)

进程调度-时间片轮转法(Java简单实现)进程调度-时间片轮转法(Java简单实现)

进程调度-时间片轮转法(Java简单实现)

进程调度-时间片轮转法(Java简单实现)



Java简单实现过程:

定义PCB类(省略了各个变量的gettersetter

public class PCB {

String name;
int cpuTime=0;
int needTime;
char state='W';

public PCB(String name,int needTime){
this.name = name;
this.needTime = needTime;
}

public void printInformation(){
System.out.println(this.getName() +"\t" + this.getCpuTime() + "\t" + this.getNeedTime() + "\t\t" + this.getState());
}
......
}

输入时间片大小和PCB数据(定义当前、就绪和完成三个队列)

<span style="white-space:pre"></span>Queue<PCB> currentQueue = new LinkedList<PCB>();
Queue<String> waitQueue = new LinkedList<String>();
Queue<String> finishQueue = new LinkedList<String>();
System.out.println("Please input the number of round");
Scanner scanner = new Scanner(System.in);
int round = scanner.nextInt();
System.out
.println("Please input the name and needTime\n(input F to finish)");
while (true) {
String name = scanner.next();
if (name.equals("F")) {
break;
}
int needTime = scanner.nextInt();
PCB inputPCB = new PCB(name, needTime);
currentQueue.offer(inputPCB);
waitQueue.offer(inputPCB.getName());
}
scanner.close();


 <span style="white-space:pre"></span>do {
// 进程调度处理
PCB processingPCB = currentQueue.poll();
if (processingPCB.state != 'F'){
waitQueue.poll();
processingPCB.setState('R');
if (processingPCB.getNeedTime() > round) {
processingPCB.setCpuTime(processingPCB.getCpuTime() + round);
processingPCB.setNeedTime(processingPCB.getNeedTime() - round);
processingPCB.setState('W');
waitQueue.offer(processingPCB.getName());
} else {
processingPCB.setCpuTime(processingPCB.getCpuTime()
+ processingPCB.getNeedTime());
processingPCB.setNeedTime(0);
processingPCB.setState('F');
finishQueue.offer(processingPCB.getName());

}

}
currentQueue.offer(processingPCB);

// 遍历输出当前队列、就绪队列、完成队列

System.out.println("-----------------------------------------");
System.out.println("round:" + round
+ "\nName\tCpuTime\tNeedTime\tState");
for (PCB outputPCB : currentQueue) {
outputPCB.printInformation();
}


System.out.print("finshQuene: ");
for (String outputFinishName : finishQueue) {
System.out.print(outputFinishName + "\t");
}
System.out.print("\n");


System.out.print("waitQuene: ");
for (String outputWaitName : waitQueue) {
System.out.print(outputWaitName + "\t");
}
System.out.print("\n");

if (waitQueue.peek() == null) {
break;
}
} while (true);

}