银行家算法java实现代码
时间: 2023-11-22 16:49:15 浏览: 72
银行家算法 JAVA
5星 · 资源好评率100%
以下是银行家算法的Java实现代码:
```java
import java.util.Scanner;
public class BankerAlgorithm {
private int[][] allocation; // 分配矩阵
private int[][] max; // 最大需求矩阵
private int[][] need; // 需求矩阵
private int[] available; // 可用资源向量
private int[] work; // 工作向量
private boolean[] finish; // 进程是否完成
public BankerAlgorithm(int[][] allocation, int[][] max, int[] available) {
this.allocation = allocation;
this.max = max;
this.available = available;
int m = allocation.length; // 进程数
int n = available.length; // 资源种类数
need = new int[m][n];
work = new int[n];
finish = new boolean[m]; // 计算需求矩阵
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
need[i][j] = max[i][j] - allocation[i][j];
}
}
}
// 判断是否能分配资源
public boolean isSafe(int i) {
int n = available.length;
for (int j = 0; j < n; j++) {
if (need[i][j] > work[j]) {
return false;
}
}
return true;
}
// 银行家算法
public boolean banker() {
int m = allocation.length; // 进程数
int n = available.length; // 资源种类数
// 初始化工作向量和finish向量
for (int i = 0; i < n; i++) {
work[i] = available[i];
}
for (int i = 0; i < m; i++) {
finish[i] = false;
}
// 找到一个可以分配的进程
int i = 0;
while (i < m && !isSafe(i)) {
i++;
}
if (i >= m) {
return false;
}
// 分配资源
for (int j = 0; j < n; j++) {
work[j] -= need[i][j];
allocation[i][j] += need[i][j];
need[i][j] = 0;
}
finish[i] = true;
// 重复上述过程,直到所有进程都完成
while (true) {
boolean flag = false;
for (i = 0; i < m; i++) {
if (!finish[i] && isSafe(i)) {
flag = true;
break;
}
}
if (!flag) {
break;
}
for (int j = 0; j < n; j++) {
work[j] -= need[i][j];
allocation[i][j] += need[i][j];
need[i][j] = 0;
}
finish[i] = true;
}
return true;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入进程数:");
int m = scanner.nextInt();
System.out.print("请输入资源种类数:");
int n = scanner.nextInt();
int[][] allocation = new int[m][n];
int[][] max = new int[m][n];
int[] available = new int[n];
System.out.println("请输入分配矩阵:");
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
allocation[i][j] = scanner.nextInt();
}
}
System.out.println("请输入最大需求矩阵:");
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
max[i][j] = scanner.nextInt();
}
}
System.out.println("请输入可用资源向量:");
for (int i = 0; i < n; i++) {
available[i] = scanner.nextInt();
}
BankerAlgorithm bankerAlgorithm = new BankerAlgorithm(allocation, max, available);
if (bankerAlgorithm.banker()) {
System.out.println("系统是安全的");
} else {
System.out.println("系统是不安全的");
}
}
}
```
阅读全文