内容:设计一个简单的进程调度算法,模拟OS中的进程调度过程;
要求:
① 进程数不少于5个;
② 进程调度算法任选;
可以用动态优先数加时间片轮转法实现进程调度,每运行一个时间片优先数减3;
package test;
import java.util.ArrayList;
import java.util.Collections;
public class Os{
public static void main(String[] args) {
ArrayList<PCB> pcb = new ArrayList<PCB>();
pcb.add(new PCB(0, 9, 0, 3));
pcb.add(new PCB(1, 38, 0, 2));
pcb.add(new PCB(2, 30, 0, 6));
pcb.add(new PCB(3, 29, 0, 3));
pcb.add(new PCB(4, 0, 0, 4));
while (!isFinish(pcb)) {
Collections.sort(pcb);
PCB p = pcb.get(0);
System.out.println("正在运行:" + p.id);
System.out.print("当前就绪队列:");
for (int i = 1; i < pcb.size(); i++) {
System.out.print(pcb.get(i).id + " ");
}
System.out.println();
p.priority -= 3;
p.cputime++;
p.alltime--;
if (p.alltime == 0) {
pcb.remove(0);
}
}
}
public static boolean isFinish(ArrayList<PCB> pcb) {
boolean flag = true;
for (PCB p : pcb) {
if (p.alltime != 0) {
flag = false;
break;
}
}
return flag;
}
}
class PCB implements Comparable<PCB> {
int id;
int priority;
int cputime;
int alltime;
public PCB(int id, int priority, int cputime, int alltime) {
super();
this.id = id;
this.priority = priority;
this.cputime = cputime;
this.alltime = alltime;
}
@Override
public int compareTo(PCB o) {
if (this.priority > o.priority) {
return -1;
} else if (this.priority < o.priority) {
return 1;
} else {
return 0;
}
}
@Override
public String toString() {
return this.priority + "";
}
}
运行截图如下:
看不懂的地方评论区留言