Round-robin 算法

Round-robin 是一种使用在 进程 和 网络分配 计算中的算法。 

以 进程分配为例:


假设我们的time slot ( 单次运行进程的最长时间) 是100 ms,  如果 job1 一共需要消耗250 ms来运行, 那么 round-robin 分配器就会暂停 job1 在其运行100 ms之后, 然后分配给其他的进程, 并且将 job1 剩下的内容放到队列中排队,直到 job1 运行结束。


Process name Arrival time Execute time
P00250
P150170
P213075
P3190100
P4210130
P535050
以上的图中表示 进程 0 - 5 的到达时间和运行完成的总时间。


运行队列如下。


时间队列解释
0P0时间0的时候, P0 到达
100P1 P0当运行100ms的时候,应该分配给下一个进程,P1在0~100内到达,P0剩下150 ms需要执行
200P0 P2 P3 P1当运行200ms的时候,新进程 P2 和 P3 在100~200内 到达,P1 剩下70ms,
300P2 P3 P1 P4 P0当运行300ms的时候,新进程P4 在200~300 内到达,P0 剩下 50ms
375P3 P1 P4 P0 P5当从300ms到375ms的时候,进程P2完成,那么我们将结束它,进而按照队列继续工作,注意把在300 ~ 375内到达的P5放进进程队列中
475P1 P4 P0 P5 P3结束, 回归下队列中的进程。P1 70ms, P4 130ms  P0 50ms P5 50ms 
545P4 P0 P5P1结束
645P0 P5 P4P4剩下30ms
695P5 P4P0结束
745P4P5结束
775 P4结束
  


public static void RoundRobin_Algo(int[] arrTime, int[] exeTime, int timeSlot) {
		if (arrTime == null || exeTime == null || arrTime.length != exeTime.length) {
			System.out.println("Error!");
		}
		
		Queue<process> queue = new LinkedList<process>();
		int index = 0;	
		int totalWaitTime = 0;		//所有进程的等待总时间
		int currentTime = 0;		//当前时间
		int visitedTimes = 0;		//CPU访问次数
		
		while (!queue.isEmpty() || index < arrTime.length) {
			if (!queue.isEmpty()) {
				visitedTimes ++;
				process tempP = queue.poll();
				//waiting time in total
				totalWaitTime += currentTime - tempP.arrTime;
				//update the currentTime
				currentTime += Math.min(tempP.exeTime, timeSlot);
				
				//add the process which arrived before the end of this process finished.
				for (; index < arrTime.length && arrTime[index] < currentTime; index++) {
					queue.add(new process(arrTime[index], exeTime[index]));
				}
				
				//add the rest of current process into process queue
				if (tempP.exeTime > timeSlot) {
					queue.add(new process(currentTime, tempP.exeTime - timeSlot));
				}
				
			} else {
				queue.add(new process(arrTime[index], exeTime[index]));
				currentTime = arrTime[index];
				index++;
				visitedTimes ++;
			}
		}
		System.out.println("Total wait time among the process: " + totalWaitTime);
		System.out.println("Total CPU visited times: " + visitedTimes);
	}


Let me know, If you found any issues.

  • 9
    点赞
  • 41
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值