java简单实现优先权算法和轮转法
时间: 2023-09-21 17:00:32 浏览: 109
1. 优先权算法在Java中的简单实现:
```java
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class PrioritySchedulingAlgorithm {
public static void main(String[] args) {
List<Process> processes = new ArrayList<>();
// 创建进程对象,并设置对应的优先级和执行时间
Process p1 = new Process("P1", 2, 10);
Process p2 = new Process("P2", 1, 5);
Process p3 = new Process("P3", 3, 8);
// 将进程添加到列表中
processes.add(p1);
processes.add(p2);
processes.add(p3);
// 根据优先级对进程进行排序
Collections.sort(processes, Comparator.comparingInt(Process::getPriority));
// 执行进程
for (Process process : processes) {
System.out.println("执行进程:" + process.getName());
for (int i = 0; i < process.getExecutionTime(); i++) {
System.out.println("执行时间片:" + (i + 1));
}
System.out.println("完成进程:" + process.getName());
}
}
static class Process {
private String name;
private int priority;
private int executionTime;
public Process(String name, int priority, int executionTime) {
this.name = name;
this.priority = priority;
this.executionTime = executionTime;
}
public String getName() {
return name;
}
public int getPriority() {
return priority;
}
public int getExecutionTime() {
return executionTime;
}
}
}
```
2. 轮转法在Java中的简单实现:
```java
import java.util.LinkedList;
import java.util.Queue;
public class RoundRobinSchedulingAlgorithm {
public static void main(String[] args) {
Queue<Process> processes = new LinkedList<>();
// 创建进程对象,并设置对应的执行时间
Process p1 = new Process("P1", 10);
Process p2 = new Process("P2", 5);
Process p3 = new Process("P3", 8);
// 将进程添加到队列中
processes.add(p1);
processes.add(p2);
processes.add(p3);
// 设置时间片长度
int timeSlice = 2;
// 执行进程
while (!processes.isEmpty()) {
Process currentProcess = processes.poll();
System.out.println("执行进程:" + currentProcess.getName());
// 执行时间片
for (int i = 0; i < timeSlice && currentProcess.getExecutionTime() > 0; i++) {
System.out.println("执行时间片:" + (i + 1));
currentProcess.reduceExecutionTime();
}
if (currentProcess.getExecutionTime() > 0) {
// 将未执行完的进程重新添加到队列中
processes.add(currentProcess);
} else {
System.out.println("完成进程:" + currentProcess.getName());
}
}
}
static class Process {
private String name;
private int executionTime;
public Process(String name, int executionTime) {
this.name = name;
this.executionTime = executionTime;
}
public String getName() {
return name;
}
public int getExecutionTime() {
return executionTime;
}
public void reduceExecutionTime() {
this.executionTime--;
}
}
}
```
以上就是在Java中简单实现优先权算法和轮转法的示例代码。这两种调度算法是常用的进程调度算法,可以根据不同的场景进行选择和使用。
阅读全文