银行家算法代码Java
时间: 2023-12-14 12:04:30 浏览: 96
以下是Java实现银行家算法的示例代码:
```java
import java.util.Scanner;
public class BankerAlgorithm {
private int[][] max; // 最大需求矩阵
private int[][] allocation; // 已分配矩阵
private int[][] need; // 需求矩阵
private int[] available; // 可用资源向量
private int processNum; // 进程数
private int resourceNum; // 资源种类数
public BankerAlgorithm(int[][] max, int[][] allocation, int[] available) {
this.max = max;
this.allocation = allocation;
this.available = available;
this.processNum = max.length; this.resourceNum = available.length;
this.need = new int[processNum][resourceNum];
for (int i = 0; i < processNum; i++) {
for (int j = 0; j < resourceNum; j++) {
need[i][j] = max[i][j] - allocation[i][j];
}
}
}
// 判断是否满足条件
private boolean check(int[] work, boolean[] finish, int[] need, int[] allocation) {
for (int i = 0; i < resourceNum; i++) {
if (need[i] > work[i]) {
return false;
}
}
for (int i = 0; i < resourceNum; i++) {
work[i] += allocation[i];
}
finish[0] = true;
return true;
}
// 执行银行家算法
public boolean run() {
int[] work = new int[resourceNum];
System.arraycopy(available, 0, work, 0, resourceNum);
boolean[] finish = new boolean[processNum];
int count = 0;
while (count < processNum) {
boolean flag = false;
for (int i = 0; i < processNum; i++) {
if (!finish[i] && check(work, finish, need[i], allocation[i])) {
flag = true;
count++;
if (count == processNum) {
return true;
}
}
}
if (!flag) {
return false;
}
}
return true;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入进程数:");
int processNum = scanner.nextInt();
System.out.print("请输入资源种类数:");
int resourceNum = scanner.nextInt();
int[][] max = new int[processNum][resourceNum];
int[][] allocation = new int[processNum][resourceNum];
int[] available = new int[resourceNum];
System.out.println("请输入最大需求矩阵:");
for (int i = 0; i < processNum; i++) {
for (int j = 0; j < resourceNum; j++) {
max[i][j] = scanner.nextInt();
}
}
System.out.println("请输入已分配矩阵:");
for (int i = 0; i < processNum; i++) {
for (int j = 0; j < resourceNum; j++) {
allocation[i][j] = scanner.nextInt();
}
}
System.out.println("请输入可用资源向量:");
for (int i = 0; i < resourceNum; i++) {
available[i] = scanner.nextInt();
}
BankerAlgorithm bankerAlgorithm = new BankerAlgorithm(max, allocation, available);
if (bankerAlgorithm.run()) {
System.out.println("系统处于安全状态");
} else {
System.out.println("系统处于不安全状态");
}
}
}
```
阅读全文
相关推荐












