Java实现短作业优先算法,PCB里需要有进程名,进程状态,运行时间、到达时间以及下一个链表所在
时间: 2024-03-16 11:48:09 浏览: 15
下面是 Java 实现短作业优先算法的示例代码:
```java
import java.util.*;
class Process {
String name;
int status;
int runTime;
int arriveTime;
Process next;
public Process(String name, int runTime, int arriveTime) {
this.name = name;
this.status = 0;
this.runTime = runTime;
this.arriveTime = arriveTime;
this.next = null;
}
}
public class SJF {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// 输入进程数量
System.out.print("请输入进程数量:");
int n = sc.nextInt();
// 输入进程信息
Process head = new Process("", 0, 0);
Process p = head;
for (int i = 0; i < n; i++) {
System.out.println("请输入第" + (i+1) + "个进程的信息(进程名 运行时间 到达时间):");
String name = sc.next();
int runTime = sc.nextInt();
int arriveTime = sc.nextInt();
Process q = new Process(name, runTime, arriveTime);
p.next = q;
p = q;
}
// 将进程按照到达时间排序
head = head.next;
Arrays.sort(head, new Comparator<Process>() {
@Override
public int compare(Process p1, Process p2) {
return p1.arriveTime - p2.arriveTime;
}
});
// 运行进程
int time = 0;
while (head != null) {
// 找到最短作业
Process q = head;
p = head.next;
while (p != null && p.arriveTime <= time) {
if (p.runTime < q.runTime) {
q = p;
}
p = p.next;
}
// 运行最短作业
System.out.println("运行进程:" + q.name);
q.status = 1;
time += q.runTime;
q = q.next;
// 删除已经运行的进程
head = head.next;
while (head != null && head.status == 1) {
head = head.next;
}
p = head;
while (p != null && p.next != null) {
if (p.next.status == 1) {
p.next = p.next.next;
} else {
p = p.next;
}
}
}
}
}
```
在这个实现中,`Process` 类表示一个进程,包含进程名、进程状态、运行时间、到达时间和下一个链表所在。`SJF` 类是主类,包含 `main` 方法。首先输入进程数量和进程信息,然后将进程按照到达时间排序。接着循环运行进程,每次找到最短作业并运行,然后删除已经运行的进程。