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

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

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

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


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







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);

	}




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值