GPT答: |
7i24.cn
|
以下是一个简单的按时间片轮转法调度算法的Java代码实现:
```java
import java.util.LinkedList;
import java.util.Queue;
public class RoundRobinScheduler {
public static void main(String[] args) {
// 创建进程队列
Queue<Process> queue = new LinkedList<>();
queue.add(new Process("P1", 10));
queue.add(new Process("P2", 5));
queue.add(new Process("P3", 8));
// 设置时间片大小为2
int timeSlice = 2;
// 模拟调度过程
while (!queue.isEmpty()) {
Process currentProcess = queue.poll();
System.out.println(currentProcess.getName() + " is running...");
if (currentProcess.getRemainingTime() > timeSlice) {
currentProcess.setRemainingTime(currentProcess.getRemainingTime() - timeSlice);
System.out.println(currentProcess.getName() + " has " + currentProcess.getRemainingTime() + "ms remaining.");
queue.offer(currentProcess); // 将当前进程重新加入队列尾部等待下一次调度
} else {
System.out.println(currentProcess.getName() + " has finished.");
}
try { Thread.sleep(timeSlice * 1000); } catch (InterruptedException e) {} // 模拟CPU执行时间片,单位为秒
}
}
}
class Process {
private String name;
private int remainingTime;
public Process(String name, int totalTime) {
this.name = name;
this.remainingTime = totalTime;
}
public String getName() { return name; }
public int getRemainingTime() { return remainingTime; }
public void setRemainingTime(int remainingTime) { this.remainingTime = remainingTime; }
}
```
在上面的代码中,我们创建了一个进程队列,并设置时间片大小为2。然后,我们模拟调度过程,在每次调度时从队列头部取出一个进程并执行它。如果该进程的剩余时间大于时间片大小,则将其重新加入队列尾部等待下一次调度;否则,该进程已经完成执行,不需要再加入队列。
在实际应用中,我们可以根据具体情况来设置时间片大小和进程数量,并使用更高级别的数据结构(如堆或红黑树)来维护就绪队列以提高效率。
|