在学习操作系统这本书的时候,我们使用的是汤小丹老师的《计算机操作系统》接下来我将会使用java语言去实现内部代码。
LRU算法
LRU算法全程为Least Recently Used置换算法,最近最久未使用(LRU)的页面置换算法是根据页面调入内存后的使用情况做出的决策。
假定系统为某进程分配了三个物理块,并考虑有以下的页面号引用串:
7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2, 1, 2, 0, 1, 7, 0, 1
当进程第一次对页面2进行访问时,由于页面7是最近最久未访问的,故将它置换出去。当进程第一次对页面3进行访问时,第一页称为最远最久未使用的页,故将它换出。以此类推。
以下是源代码实现部分:
package chapter02;
public class P176LRU {
//查找元素是否在数组中存在
public static int paramExist(int[] place,int param){
for (int i = 0; i < place.length; i++) {
if(place[i]==param)
return i;
}
//不为空
return -1;
}
//查找元素是否在数组中存在
public static void ChangePlaceCount(int[] placeIndex,int NotNeedIndex){
for (int i = 0; i < placeIndex.length; i++) {
if(i==NotNeedIndex)
placeIndex[i]=0;
else
placeIndex[i]++;
}
}
//获取最大距离值
public static int getMaxIndexOfCount(int[] place,int[] placeCount){
int maxCount = placeCount[0];
int maxIndex = 0;
for(int i = 0;i<placeCount.length;i++){
if(placeCount[i]>maxCount){
maxCount = placeCount[i];
maxIndex = i;
}
}
return maxIndex;
}
public static void main(String[] args) {
int[] block = new int[]{7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2, 1, 2, 0, 1, 7, 0, 1};
int max = block.length;
int[] place = new int[]{-1,-1, -1};
int[] placeCount = new int[]{max,max,max};
for (int index = 0; index < block.length; index++) {
//假设元素存在则不需要进行任何操作
int exitsIndex = paramExist(place,block[index]);
if(exitsIndex!=-1){
//当前existIndex需要清零,其他的需要进行++
ChangePlaceCount(placeCount,exitsIndex);
continue;
}
//元素不存在,即为-1
else {
int maxIndex = getMaxIndexOfCount(place,placeCount);
place[maxIndex] = block[index];
ChangePlaceCount(placeCount,maxIndex);
for (int param : place) {
System.out.print(param + " ");
}
System.out.println();
}
}
}
}
实验结果:
"C:\Program Files\Java\jdk1.8.0_101\bin\java.exe"
7 -1 -1
7 0 -1
7 0 1
2 0 1
2 0 3
4 0 3
4 0 2
4 3 2
0 3 2
1 3 2
1 0 2
1 0 7
Process finished with exit code 0