进程调度-优先级算法(Java简单实现)

来源:互联网 发布:睡觉 知乎 编辑:程序博客网 时间:2024/06/05 02:10

在时间片轮转调度算法中,做了一个隐含的假设,即系统中所有进程的紧迫性是相同的。但实际情况并非如此,为了能满足实际情况的需要,在进程调度算法中引入优先级,而形成优先级调度算法。


本例中实现的优先级的定义为:

 优先数 = 50 - 运行时间

 每运行一次优先数减3,重新竞争。


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





Java实现过程

PCB类在比起时间片轮转算法中新增一个priorityNumber(省略了各个变量的gettersetter

public class PCB {String name;int priorityNumber=50;int cpuTime=0;int needTime;char state='W';public PCB(String name,int needTime){this.name = name;this.needTime = needTime;this.priorityNumber = 50-needTime;}public void printInformation(){System.out.println(this.getName() +"\t" + this.getCpuTime() + "\t" + this.getNeedTime() + "\t\t" + this.getState());}......}

循环一下处理过程并输出

// 找出优先级最高的进程int maxPriorityNumber = 0;for (PCB tempPCB : currentQueue) {if(tempPCB.getPriorityNumber()>maxPriorityNumber){maxPriorityNumber=tempPCB.getPriorityNumber();}}// 把优先级最高的进程调配到队首while(currentQueue.peek().getPriorityNumber() < maxPriorityNumber){currentQueue.offer(currentQueue.peek());currentQueue.poll();}
进程调度处理

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');} else {processingPCB.setCpuTime(processingPCB.getCpuTime()+ processingPCB.getNeedTime());processingPCB.setNeedTime(0);processingPCB.setState('F');}// 执行完毕竞争数减3}currentQueue.offer(processingPCB);
遍历输出结果(略)







0 0
原创粉丝点击