银行家算法java代码可视化界面
时间: 2023-09-10 09:01:19 浏览: 138
银行家算法是一种用于管理操作系统资源分配的算法,保证系统能够分配资源而不导致死锁的发生。以下是一个简单的用Java编写的银行家算法可视化界面代码示例:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class BankerVisualizer extends JFrame {
private JButton allocateButton;
private JTextField inputField;
private int[] available = {10, 5, 7};
private int[][] max = {{7, 5, 3}, {3, 2, 2}, {9, 0, 2}};
private int[][] allocation = {{0, 1, 0}, {2, 0, 0}, {3, 0, 2}};
private int[][] need = {{7, 4, 3}, {1, 2, 2}, {6, 0, 0}};
public BankerVisualizer() {
setTitle("银行家算法可视化界面");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
allocateButton = new JButton("分配资源");
inputField = new JTextField(20);
allocateButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String input = inputField.getText();
String[] resourceString = input.split(",");
int[] request = new int[resourceString.length];
for (int i = 0; i < resourceString.length; i++) {
request[i] = Integer.parseInt(resourceString[i]);
}
if (isSafe(request)) {
for (int i = 0; i < resourceString.length; i++) {
available[i] -= request[i];
allocation[0][i] += request[i];
need[0][i] -= request[i];
}
JOptionPane.showMessageDialog(null, "资源分配成功!");
} else {
JOptionPane.showMessageDialog(null, "资源分配失败,可能会导致死锁!");
}
inputField.setText("");
}
});
setLayout(new FlowLayout());
add(new JLabel("资源请求向量(格式:resource1,resource2,resource3):"));
add(inputField);
add(allocateButton);
}
private boolean isSafe(int[] request) {
int[] work = available.clone();
boolean[] finish = new boolean[allocation.length];
boolean safe = true;
for (int i = 0; i < finish.length; i++) {
finish[i] = false;
}
// 计算need矩阵和work向量
int[][] tempNeed = need.clone();
int[] tempWork = work.clone();
for (int i = 0; i < tempNeed.length; i++) {
for (int j = 0; j < tempNeed[i].length; j++) {
tempNeed[i][j] -= request[j];
tempWork[j] -= request[j];
}
}
// 死锁检测
while (true) {
boolean flag = false;
for (int i = 0; i < finish.length; i++) {
if (!finish[i] && isLessThanOrEqualTo(tempNeed[i], tempWork)) {
for (int j = 0; j < tempNeed[i].length; j++) {
tempWork[j] += allocation[i][j];
}
finish[i] = true;
flag = true;
}
}
if (!flag) {
break;
}
}
// 检查是否有进程未完成
for (boolean f : finish) {
if (!f) {
safe = false;
break;
}
}
return safe;
}
private boolean isLessThanOrEqualTo(int[] array1, int[] array2) {
for (int i = 0; i < array1.length; i++) {
if (array1[i] > array2[i]) {
return false;
}
}
return true;
}
public static void main(String[] args) {
BankerVisualizer bankerVisualizer = new BankerVisualizer();
bankerVisualizer.setVisible(true);
}
}
```
上述代码实现了一个简单的银行家算法可视化界面,用户可以在界面上输入资源请求向量,点击按钮后根据银行家算法判断是否可以分配资源。如果可以分配资源,则更新各个矩阵(available、allocation、need),否则提示分配失败。
阅读全文