时间片轮转调度算法

时间:2021-11-28 19:48:05

时间片轮转调度算法:每个进程被分配一个时间段,称作它的时间片,即该进程允许运行的时间。如果在时间片结束时进程还在运行,则CPU将被剥夺并分配给另一个进程。如果进程在时间片结束前阻塞或结束,则CPU当即进行切换。调度程序所要做的就是维护一张就绪进程列表,当进程用完它的时间片后,它被移到队列的末尾。

public class process {

/**
* @param args
*/
public static void RR(int[] arriveTime,int[] serviceTime,int q){
Queue<Integer> queue=new LinkedList<Integer>();
queue.offer(0);
int[] temp=new int[arriveTime.length];
for(int s=0;s<serviceTime.length;s++){
temp[s]=serviceTime[s];
}
int[] finishTime=new int[serviceTime.length];
int j;
int i=1;
int time=finishTime[0];
int count=0;
for(int m=0;m<arriveTime.length;m++)
count+=serviceTime[m];
int tmp=-1;
while(!queue.isEmpty()){
temp[queue.peek()]=temp[queue.peek()]-q;
if(temp[queue.peek()]>=0){
time=q+time;
finishTime[queue.peek()]=time;
}
if(temp[queue.peek()]<0){
time=temp[queue.peek()]+q+time;
finishTime[queue.peek()]=time;
temp[queue.peek()]=0;
}
for(j=i;j<arriveTime.length;j++){
if(arriveTime[j]<=time){
queue.offer(j);
i++;
}else
continue;
}
if(temp[queue.peek()]==0){
finishTime[queue.peek()]=time;
if(queue.isEmpty()!=true){
queue.poll();
}
}
else{
tmp=queue.peek();
queue.poll();
queue.offer(tmp);
}
}


int[] waitTime=new int[arriveTime.length];
int waitTimeTotal=0;
for(int jj=0;jj<arriveTime.length;jj++){
waitTime[jj]=finishTime[jj]-arriveTime[jj];
waitTimeTotal+=waitTime[jj];
}
double aveWaitTime=(double)waitTimeTotal/arriveTime.length;
System.out.println(aveWaitTime);

}

public static void main(String[] args) {
// TODO Auto-generated method stub
int[] arrive={0,1,2,3,4};
int[] service={6,2,5,9,8};
RR(arrive,service,4);

}

}