用java实现图形化进程调度代码
时间: 2023-09-30 07:09:46 浏览: 91
进程调度的源代码(java语言)
3星 · 编辑精心推荐
以下是一个使用Java Swing实现的简单图形化进程调度的示例代码:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ProcessScheduler extends JFrame {
private JPanel processPanel;
private JTextArea logTextArea;
private int time = 0;
private int quantum = 2;
private Process[] processes = {
new Process("P1", 5, 2),
new Process("P2", 4, 1),
new Process("P3", 3, 5),
new Process("P4", 2, 4),
new Process("P5", 1, 3)
};
private int currentProcessIndex = 0;
public ProcessScheduler() {
super("Process Scheduler");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 300);
setLayout(new BorderLayout());
processPanel = new JPanel();
processPanel.setLayout(new GridLayout(processes.length, 3));
for (int i = 0; i < processes.length; i++) {
processPanel.add(new JLabel(processes[i].getName()));
processPanel.add(new JLabel(String.valueOf(processes[i].getBurstTime())));
processPanel.add(new JLabel(String.valueOf(processes[i].getPriority())));
}
add(processPanel, BorderLayout.CENTER);
JButton runButton = new JButton("Run");
runButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
runProcesses();
}
});
add(runButton, BorderLayout.SOUTH);
logTextArea = new JTextArea();
add(new JScrollPane(logTextArea), BorderLayout.EAST);
setVisible(true);
}
private void runProcesses() {
while (!allProcessesFinished()) {
Process currentProcess = processes[currentProcessIndex];
if (currentProcess.getBurstTime() > 0) {
currentProcess.setBurstTime(currentProcess.getBurstTime() - quantum);
time += quantum;
logTextArea.append("Process " + currentProcess.getName() + " runs for " + quantum + "ms. " + currentProcess.getBurstTime() + "ms remaining.\n");
}
currentProcessIndex = (currentProcessIndex + 1) % processes.length;
}
logTextArea.append("All processes finished in " + time + "ms.\n");
}
private boolean allProcessesFinished() {
for (int i = 0; i < processes.length; i++) {
if (processes[i].getBurstTime() > 0) {
return false;
}
}
return true;
}
public static void main(String[] args) {
new ProcessScheduler();
}
}
class Process {
private String name;
private int burstTime;
private int priority;
public Process(String name, int burstTime, int priority) {
this.name = name;
this.burstTime = burstTime;
this.priority = priority;
}
public String getName() {
return name;
}
public int getBurstTime() {
return burstTime;
}
public void setBurstTime(int burstTime) {
this.burstTime = burstTime;
}
public int getPriority() {
return priority;
}
}
```
这个示例实现了一个简单的轮转调度算法,每个进程运行quantum时间片后切换到下一个进程,直到所有进程都运行完毕。界面中显示了每个进程的名称、运行时间和优先级,同时也提供了一个运行按钮来开始进程调度。当进程运行时,会在日志区域显示每个进程的运行情况,包括运行时间和剩余时间。当所有进程都运行完毕后,会在日志区域显示总运行时间。
阅读全文