银行家算法JAVA代码
时间: 2023-11-17 16:05:59 浏览: 65
银行家算法是一种避免死锁的算法,它可以通过安全性检查来避免系统进入不安全状态。下面是一个简单的银行家算法的JAVA代码实现:
```java
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];
}
}
}
public boolean isSafe() {
boolean[] finish = new boolean[processNum];
int[] work = new int[resourceNum];
for (int i = 0; i < resourceNum; i++) {
work[i] = available[i];
}
int count = 0;
while (count < processNum) {
boolean flag = false;
for (int i = 0; i < processNum; i++) {
if (!finish[i]) {
boolean temp = true;
for (int j = 0; j < resourceNum; j++) {
if (need[i][j] > work[j]) {
temp = false;
break;
}
}
if (temp) {
for (int j = 0; j < resourceNum; j++) {
work[j] += allocation[i][j];
}
finish[i] = true;
flag = true;
count++;
}
}
}
if (!flag) {
return false;
}
}
return true;
}
}
```