Javaswing图形化实现模拟进程调度算法具体代码
时间: 2024-03-16 13:47:51 浏览: 133
以下是一个简单的Java Swing程序,它可以模拟先来先服务(FCFS)进程调度算法,并在图形化界面中显示进程和CPU状态。
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
public class ProcessScheduler extends JFrame implements ActionListener {
private DefaultTableModel model;
private JTable table;
private JButton button;
private JLabel label;
private JPanel panel;
private int time;
private int index;
private int[] arrivalTime = {0, 1, 2, 3, 4};
private int[] serviceTime = {4, 3, 5, 2, 4};
private int[] remainingTime;
private int[] completionTime;
private int[] turnaroundTime;
private int[] waitingTime;
public ProcessScheduler() {
setTitle("Process Scheduler");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(500, 300);
setLocationRelativeTo(null);
setLayout(new BorderLayout());
model = new DefaultTableModel(new String[] {"Process", "Arrival Time", "Service Time", "Completion Time", "Turnaround Time", "Waiting Time"}, 0);
table = new JTable(model);
JScrollPane scrollPane = new JScrollPane(table);
add(scrollPane, BorderLayout.CENTER);
button = new JButton("Start");
button.addActionListener(this);
add(button, BorderLayout.SOUTH);
label = new JLabel("Time: 0", SwingConstants.CENTER);
add(label, BorderLayout.NORTH);
panel = new JPanel(new GridLayout(1, 4));
add(panel, BorderLayout.EAST);
panel.add(new JLabel("CPU"));
panel.add(new JLabel("Time"));
panel.add(new JLabel("Process"));
panel.add(new JLabel("Remaining Time"));
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button) {
button.setEnabled(false);
time = 0;
index = 0;
remainingTime = serviceTime.clone();
completionTime = new int[arrivalTime.length];
turnaroundTime = new int[arrivalTime.length];
waitingTime = new int[arrivalTime.length];
while (true) {
boolean done = true;
for (int i = 0; i < arrivalTime.length; i++) {
if (arrivalTime[i] <= time && remainingTime[i] > 0) {
done = false;
remainingTime[i]--;
label.setText("Time: " + time);
table.setValueAt("CPU", index, 0);
table.setValueAt(time, index, 1);
table.setValueAt(i + 1, index, 2);
table.setValueAt(remainingTime[i], index, 3);
if (remainingTime[i] == 0) {
completionTime[i] = time + 1;
turnaroundTime[i] = completionTime[i] - arrivalTime[i];
waitingTime[i] = turnaroundTime[i] - serviceTime[i];
}
index++;
}
}
if (done) {
break;
}
time++;
}
for (int i = 0; i < arrivalTime.length; i++) {
model.addRow(new Object[] {i + 1, arrivalTime[i], serviceTime[i], completionTime[i], turnaroundTime[i], waitingTime[i]});
}
}
}
public static void main(String[] args) {
new ProcessScheduler();
}
}
```
这个程序的主要功能是在模拟进程调度算法的过程中更新图形化界面的显示。它使用了JTable来显示进程的属性,用JButton来启动模拟进程调度算法,用JLabel来显示当前的时间,用JPanel来显示CPU的状态。在实现逻辑上,它使用了一个while循环来模拟进程的调度和执行,并使用了一个数组来存储进程的属性。在每个进程执行完成后,它会将该进程的属性添加到JTable中,并计算出该进程的完成时间、周转时间和等待时间。
阅读全文