页面置换算法OPTjava实现
时间: 2023-11-26 12:47:06 浏览: 65
以下是页面置换算法OPT的Java实现:
```java
import java.util.*;
public class Opt {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("请输入物理块数量:");
int frameNum = sc.nextInt();
System.out.print("请输入访问页面总数:");
int pageNum = sc.nextInt();
int[] pages = new int[pageNum];
System.out.print("请输入要访问的页面号(以空格分隔):");
for (int i = 0; i < pageNum; i++) {
pages[i] = sc.nextInt();
}
sc.close();
int[] frames = new int[frameNum];
int[] nextUse = new int[frameNum];
Arrays.fill(frames, -1);
Arrays.fill(nextUse, pageNum);
int pageFault = 0;
for (int i = 0; i < pageNum; i++) {
int page = pages[i];
boolean hit = false;
for (int j = 0; j < frameNum; j++) {
if (frames[j] == page) {
hit = true;
break;
}
}
if (!hit) {
pageFault++;
int victim = 0;
for (int j = 1; j < frameNum; j++) {
if (nextUse[j] > nextUse[victim]) {
victim = j;
}
}
frames[victim] = page;
}
for (int j = 0; j < frameNum; j++) {
if (frames[j] != -1) {
nextUse[j] = Integer.MAX_VALUE;
for (int k = i + 1; k < pageNum; k++) {
if (pages[k] == frames[j]) {
nextUse[j] = k;
break;
}
}
}
}
}
double pageFaultRate = (double) pageFault / pageNum;
System.out.println("缺页次数:" + pageFault);
System.out.println("缺页率:" + pageFaultRate);
}
}
```
阅读全文