多级反馈队列抢占式java实现
时间: 2023-04-12 22:01:54 浏览: 186
java实现多级反馈队列算法,允许处理机空闲
可以使用Java中的PriorityQueue和Thread类来实现多级反馈队列抢占式调度算法。具体实现可以参考以下代码:
import java.util.PriorityQueue;
public class MultiLevelFeedbackQueue {
private PriorityQueue<Process> readyQueue;
private Thread currentThread;
private int timeSlice;
public MultiLevelFeedbackQueue(int timeSlice) {
readyQueue = new PriorityQueue<>();
currentThread = null;
this.timeSlice = timeSlice;
}
public void addProcess(Process process) {
readyQueue.add(process);
}
public void run() {
while (!readyQueue.isEmpty()) {
Process process = readyQueue.poll();
currentThread = new Thread(process);
currentThread.start();
try {
Thread.sleep(timeSlice);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (process.isAlive()) {
readyQueue.add(process);
}
}
}
}
class Process implements Runnable, Comparable<Process> {
private int priority;
private int timeLeft;
public Process(int priority, int timeLeft) {
this.priority = priority;
this.timeLeft = timeLeft;
}
@Override
public void run() {
while (timeLeft > 0) {
timeLeft--;
}
}
@Override
public int compareTo(Process o) {
return Integer.compare(priority, o.priority);
}
public boolean isAlive() {
return timeLeft > 0;
}
}
注意:以上代码仅供参考,实际应用中需要根据具体需求进行修改和完善。
阅读全文