Java实现短作业优先算法,PCB里需要有进程名,进程状态,运行时间、到达时间以及下一个链表所在
时间: 2024-03-17 14:40:41 浏览: 186
这是一个简单的 Java 实现短作业优先算法的例子,包含了 PCB 中需要的进程名、进程状态、运行时间、到达时间以及下一个链表所在:
```java
import java.util.*;
public class SJF {
public static void main(String[] args) {
List<PCB> readyQueue = new ArrayList<>(); // 就绪队列
readyQueue.add(new PCB("P1", PCB.State.READY, 5, 0));
readyQueue.add(new PCB("P2", PCB.State.READY, 3, 2));
readyQueue.add(new PCB("P3", PCB.State.READY, 8, 4));
readyQueue.add(new PCB("P4", PCB.State.READY, 2, 5));
readyQueue.add(new PCB("P5", PCB.State.READY, 4, 7));
// 按照到达时间排序
Collections.sort(readyQueue, Comparator.comparingInt(PCB::getArrivalTime));
// 从就绪队列中选出运行时间最短的进程
PCB runningProcess = null;
int currentTime = 0;
do {
for (PCB pcb : readyQueue) {
if (pcb.getState() == PCB.State.READY && pcb.getArrivalTime() <= currentTime &&
(runningProcess == null || pcb.getRunTime() < runningProcess.getRunTime())) {
runningProcess = pcb;
}
}
if (runningProcess != null) {
runningProcess.setState(PCB.State.RUNNING);
runningProcess.setStartTime(currentTime);
currentTime += runningProcess.getRunTime();
runningProcess.setFinishTime(currentTime);
runningProcess.setState(PCB.State.FINISHED);
runningProcess = null;
} else {
currentTime++;
}
} while (readyQueue.stream().anyMatch(pcb -> pcb.getState() != PCB.State.FINISHED));
// 输出结果
for (PCB pcb : readyQueue) {
System.out.println(pcb.getName() + " " + pcb.getStartTime() + " " + pcb.getFinishTime());
}
}
}
class PCB {
enum State {
READY, RUNNING, FINISHED
}
private String name; // 进程名
private State state; // 进程状态
private int runTime; // 运行时间
private int arrivalTime; // 到达时间
private int startTime; // 开始时间
private int finishTime; // 完成时间
public PCB(String name, State state, int runTime, int arrivalTime) {
this.name = name;
this.state = state;
this.runTime = runTime;
this.arrivalTime = arrivalTime;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public State getState() {
return state;
}
public void setState(State state) {
this.state = state;
}
public int getRunTime() {
return runTime;
}
public void setRunTime(int runTime) {
this.runTime = runTime;
}
public int getArrivalTime() {
return arrivalTime;
}
public void setArrivalTime(int arrivalTime) {
this.arrivalTime = arrivalTime;
}
public int getStartTime() {
return startTime;
}
public void setStartTime(int startTime) {
this.startTime = startTime;
}
public int getFinishTime() {
return finishTime;
}
public void setFinishTime(int finishTime) {
this.finishTime = finishTime;
}
}
```
这里用到了一个 PCB 类来存储进程的相关信息,通过就绪队列来模拟进程的调度。其中,`Comparator.comparingInt(PCB::getArrivalTime)` 表示按照到达时间排序,`runningProcess == null || pcb.getRunTime() < runningProcess.getRunTime()` 表示选出运行时间最短的进程。
阅读全文