简单模拟一下内存分页,分配和回收。这里我就用最最最简化的方式没有技术含量。
每个进程维护一张页表,然后操作系统用位示图模拟内存分配情况(0: 未分配,1已经分配)
import java.util.*;public class Main {public static int PAGE_COUNT = 1024;public static int reminder;//空闲public static int[][] nums;public static void main(String[] args) {nums = new int[3][4];//方便测试,模拟页数for (int i = 0; i < nums.length; i++) {for (int j = 0; j < nums[0].length; j++) {nums[i][j] = (int) (Math.random() * 2);if (nums[i][j] == 0) {reminder++;}}}System.out.println("\n------------------------分配前--------------------------");print();//分配PCB p1 = new PCB("p1", 4);allocate(p1, 4);System.out.println("\n------------------------分配后--------------------------");print();setFree(p1);System.out.println("\n------------------------回收后--------------------------");print();}//打印内存分配情况private static void print() {for (int i = 0; i < nums.length; i++) {for (int j = 0; j < nums[0].length; j++) {System.out.print(nums[i][j] + " ");}System.out.println();}}/*** @param pcb 进程名* @param size 需要的页数*/private static void allocate(PCB pcb, int size) {if (reminder < size) {System.out.println("可分配空间不足!");}int[] pageTable = pcb.pageTable;int index = 0;for (int i = 0; i < nums.length; i++) {for (int j = 0; j < nums[0].length; j++) {if (nums[i][j] == 0) {nums[i][j] = 1;//将其分配出去pageTable[index] = i * nums[0].length + j;reminder--;if (++index == size) {System.out.println("分配完成");return;}}}}}/*** 将为该进程分配的内存回收掉** @param pcb 进程*/private static void setFree(PCB pcb) {int[] pageTable = pcb.pageTable;for (int i = 0; i < pageTable.length; i++) {//定位位示图位置int row = pageTable[i] / nums[0].length;int col = pageTable[i] % nums[0].length;//将空间回收nums[row][col] = 0;reminder++;}System.out.println("进程空间已释放!");}
}class PCB {String name;int[] pageTable;public PCB() {}public PCB(String name, int size) {//size为占用的内存页数this.name = name;this.pageTable = new int[size];Arrays.fill(this.pageTable, -1);}
}
运行截图: