天天看点

java实现首次适应算法 操作系统实验

因为操作系统实验需要,所以就花了点时间做了个首次适应算法的java实现

任务要求

编程实现首次适应算法。已知作业名、作业大小、作业提交时间、内存容量、碎片大小,要求使用分区大小不等的内存分区方法和首次适应分配算法给每次到来的作业分配内存。输出内存分区情况和分配情况。

首次适应算法(first fit):

空闲分区按地址递增的次序排列。在分配内存时,从链首开始顺序查找,直至找到一个大小能满足要求的空闲分区为止;如果分区大小-作业大小<=碎片,则直接分配,否则,按照作业的大小,从该分区中划出一块内存空间分配给请求者,余下的空闲分区仍留在空闲链中。若从链首直至链尾都不能找到一个能满足要求的分区,则此次内存分配失败,返回。

释放作业的代码

private void release(Process p) {
		Node head=header;
		int start=p.start;
		int end=p.start+p.size;
		//选择处理
		//处理作业前有空闲区
		while(head!=null) {
			//作业前有空闲区
			//两种情况
			if(getBack(head)==start) {
				//两个空闲分区,夹着
				if(head.next!=null && head.next.start==end) {//两个空闲区间以及作业,三个合并
					head.size+=head.next.size+p.size;
					head.next=head.next.next;
				}else {//回收区后没有了,或者是另一个作业
					head.size+=p.size;
				}
				return ;
			}else if(head.start==end){//处理作业前没有空闲区,作业后有空闲区
				head.start-=p.size;
				head.size+=p.size;
				return;
			} 
			head=head.next;
		}
		//处理作业夹在两个作业中间
		insertNode(p);
	}
           

作业加入的算法

public boolean insertAfter(Process p) {
		Node head=header;
		int ii=0;
		int size=p.size;
		while(head.size<size) {
			if(head.next==null) {
				System.out.println("内存不足分配失败!!");
				return false;
			}
			head=head.next;
			ii++;
		}
		//找到对应的空闲Node
		p.start=head.start+head.size-p.size;
		//判断碎片大小
		if(head.size-size<=lessSize) {
			p.size=head.size;
			deleteNode(head);
			return true;
		}
		if(ii==0) {
			header.size-=size;
			return true;
		}
		head.size-=size;
		return true;
	}
           

项目已上传到git,需要的可以下载

https://github.com/coder-oyz/data/tree/test6