用JAVA实现FIFO算法和LUR算法
时间: 2023-11-10 17:16:00 浏览: 92
FIFO算法和LUR算法都是常见的缓存置换算法,下面分别给出JAVA实现。
FIFO算法实现:
```java
import java.util.*;
public class FIFO {
private Queue<Integer> cache;
private int capacity;
public FIFO(int capacity) {
this.capacity = capacity;
cache = new LinkedList<>();
}
public void refer(int page) {
if (!cache.contains(page)) {
if (cache.size() == capacity) {
cache.remove();
}
cache.add(page);
}
}
public void display() {
System.out.println(cache);
}
public static void main(String[] args) {
FIFO cache = new FIFO(3);
cache.refer(1);
cache.refer(2);
cache.refer(3);
cache.refer(4);
cache.refer(1);
cache.refer(2);
cache.display();
}
}
```
LUR算法实现:
```java
import java.util.*;
public class LRU {
private LinkedHashMap<Integer, Integer> cache;
private int capacity;
public LRU(int capacity) {
this.capacity = capacity;
cache = new LinkedHashMap<>();
}
public void refer(int page) {
if (cache.containsKey(page)) {
cache.remove(page);
} else if (cache.size() == capacity) {
Iterator<Map.Entry<Integer, Integer>> iterator = cache.entrySet().iterator();
iterator.next();
iterator.remove();
}
cache.put(page, page);
}
public void display() {
System.out.println(cache.keySet());
}
public static void main(String[] args) {
LRU cache = new LRU(3);
cache.refer(1);
cache.refer(2);
cache.refer(3);
cache.refer(4);
cache.refer(1);
cache.refer(2);
cache.display();
}
}
```
阅读全文