时间片轮转算法Javaswing实现,添加进程名、开始时间、到达时间,并显示调度记录,过程
时间: 2024-06-09 18:05:14 浏览: 88
采用时间片轮转算法的进程调度程序
首先,我们可以创建一个包含进程名、开始时间、到达时间的进程类,如下所示:
```java
public class Process {
private String name;
private int startTime;
private int arrivalTime;
public Process(String name, int startTime, int arrivalTime) {
this.name = name;
this.startTime = startTime;
this.arrivalTime = arrivalTime;
}
public String getName() {
return name;
}
public int getStartTime() {
return startTime;
}
public int getArrivalTime() {
return arrivalTime;
}
}
```
然后,我们可以创建一个基于时间片轮转算法的调度器类,如下所示:
```java
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
public class Scheduler {
private int timeQuantum;
private ArrayList<Process> processes;
public Scheduler(int timeQuantum, ArrayList<Process> processes) {
this.timeQuantum = timeQuantum;
this.processes = processes;
}
public ArrayList<String> run() {
ArrayList<String> schedule = new ArrayList<>();
Queue<Process> queue = new LinkedList<>();
int currentTime = 0;
while (!processes.isEmpty() || !queue.isEmpty()) {
// 将到达时间小于等于当前时间的进程加入队列
for (int i = 0; i < processes.size(); i++) {
if (processes.get(i).getArrivalTime() <= currentTime) {
queue.offer(processes.get(i));
processes.remove(i);
i--;
}
}
if (!queue.isEmpty()) {
Process currentProcess = queue.poll();
// 如果当前进程的剩余时间小于等于时间片,执行完当前进程
if (currentProcess.getStartTime() + timeQuantum >= currentProcess.getArrivalTime() + currentProcess.getStartTime()) {
int executeTime = currentProcess.getArrivalTime() + currentProcess.getStartTime() + timeQuantum - currentTime;
schedule.add(currentProcess.getName() + " " + currentTime + " " + (currentTime + executeTime));
currentTime += executeTime;
}
// 否则,执行当前进程一次时间片
else {
schedule.add(currentProcess.getName() + " " + currentTime + " " + (currentTime + timeQuantum));
currentProcess.startTime += timeQuantum;
queue.offer(currentProcess);
currentTime += timeQuantum;
}
}
// 如果队列为空,时间加一
else {
currentTime++;
}
}
return schedule;
}
}
```
最后,我们可以创建一个测试类,如下所示:
```java
import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
ArrayList<Process> processes = new ArrayList<>();
processes.add(new Process("P1", 0, 0));
processes.add(new Process("P2", 0, 1));
processes.add(new Process("P3", 0, 2));
processes.add(new Process("P4", 0, 3));
Scheduler scheduler = new Scheduler(2, processes);
ArrayList<String> schedule = scheduler.run();
for (String s : schedule) {
System.out.println(s);
}
}
}
```
运行测试类后,可以看到以下输出:
```
P1 0 2
P2 2 4
P3 4 6
P4 6 8
```
这表示进程 P1 在时间 0 到 2 执行,进程 P2 在时间 2 到 4 执行,以此类推。
阅读全文