操作系统中的LRU置换算法的实现(java实现)

在学习操作系统这本书的时候,我们使用的是汤小丹老师的《计算机操作系统》接下来我将会使用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

 

 

  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值